英文:
Why the function append in Go work with reference when pass a slice?
问题
在下面的代码中,我试图向一个切片的切片中添加一个元素,但是由于Go语言使用引用,我该如何通过使用切片b的值来实现呢?
package main
import (
"fmt"
)
func main() {
a := []int{1}
arr := [][]int{a}
b := []int{2}
arr = append(arr, b)
fmt.Println(arr)
b[0] = 3
arr = append(arr, b)
fmt.Println(arr)
}
我期望最后的Println输出是[[1] [2] [3]],但实际输出是[[1] [3] [3]]。
英文:
In the next code I'm trying to add an element of a slice of slices, but as Go works with reference, how can I use this by using the b slice by value?
package main
import (
"fmt"
)
func main() {
a := []int{1}
arr := [][]int{a}
b := []int{2}
arr = append(arr, b)
fmt.Println(arr)
b[0] = 3
arr = append(arr, b)
fmt.Println(arr)
}
I expected that the last Println was [[1] [2] [3]], but it's [[1] [3] [3]].
答案1
得分: 3
没有办法通过值来插入一个切片;在插入之前,你需要对切片进行复制:
package main
import (
"fmt"
)
func copy_ints(c []int) []int {
s := make([]int, len(c))
copy(s, c)
return s
}
func main() {
a := []int{1}
arr := [][]int{copy_ints(a)}
b := []int{2}
arr = append(arr, copy_ints(b))
fmt.Println(arr)
b[0] = 3
arr = append(arr, copy_ints(b))
fmt.Println(arr)
}
你可以在这里运行这段代码。
英文:
There is no way to insert a slice "by value"; you need to make a copy of the slice before inserting it:
package main
import (
"fmt"
)
func copy_ints(c []int) []int {
s := make([]int, len(c))
copy(s, c)
return s
}
func main() {
a := []int{1}
arr := [][]int{copy_ints(a)}
b := []int{2}
arr = append(arr, copy_ints(b))
fmt.Println(arr)
b[0] = 3
arr = append(arr, copy_ints(b))
fmt.Println(arr)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论