gpt4 book ai didi

go - 在另一个函数中更改golang slice

转载 作者:行者123 更新时间:2023-12-01 20:27:30 25 4
gpt4 key购买 nike

我有一个 slice ,如果我直接在主函数中从中删除一个元素,则 slice 的长度将减少一。但是在另一个函数中执行remove并在主函数中调用它, slice 的长度仍然保持原点。谁能为我解释?谢谢!

package main

import "fmt"

func main() {
a := []int{1, 2, 3, 4}
i := 0

//copy(a[i:], a[i+1:])
//a[len(a)-1] = 0
//a = a[:len(a)-1]
//fmt.Println(a) //outputs: [2 3 4], this is correct

f(a, i)
fmt.Println(a) //outputs: [2 3 4 0], this is wrong!
}

func f(a []int, i int) {
copy(a[i:], a[i+1:])
a[len(a)-1] = 0
a = a[:len(a)-1]
fmt.Println(a) //outputs: [2 3 4], here still correct
}

Go Playground Link

最佳答案

slice 按值传递,因此在函数f中对其进行更改不会在main函数中对其进行更改。您可以像这样通过指针传递:

package main

import "fmt"

func main() {
a := []int{1, 2, 3, 4}
i := 0

f(&a, i)
fmt.Println(a) //outputs: [2 3 4], correct
}

func f(a *[]int, i int) {
b := *a
copy(b[i:], b[i+1:])
// The following line seems pointless, but ok...
b[len(b)-1] = 0
b = b[:len(b)-1]
fmt.Println(b) //outputs: [2 3 4], here still correct
*a = b
}

Go Playground

正如@zerkms在评论中所建议的那样,您还可以返回新的 slice ,从而避免使用指针:

package main

import "fmt"

func main() {
a := []int{1, 2, 3, 4}
i := 0

a = f(a, i)
fmt.Println(a)
}

func f(a []int, i int) []int {
copy(a[i:], a[i+1:])
// The following line seems pointless, but ok...
a[len(a)-1] = 0
a = a[:len(a)-1]
fmt.Println(a) //outputs: [2 3 4], here still correct
return a
}

关于go - 在另一个函数中更改golang slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58516240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com