在Go中,我试图为我的旅行推销员问题做一个混乱的切片函数。在这样做的时候,我注意到当我开始编辑切片时,我给出的扰码函数在每次传入时都是不同的。
经过一些调试,我发现这是因为我编辑了函数中的切片。但既然围棋被认为是一种“通过价值传递”的语言,这怎么可能呢?
https://play.golang.org/p/mMivoH0TuV
我提供了一个操场链接来展示我的意思。通过删除第27行,您将得到一个与保留它不同的输出,这不会产生什么影响,因为函数应该在作为参数传入时创建自己的切片副本。
有人能解释一下这个现象吗?
发布于 2021-04-23 16:08:54
为了补充这篇文章,下面是您共享的Golang PlayGround的引用传递示例:
type point struct {
x int
y int
}
func main() {
data := []point{{1, 2}, {3, 4}, {5, 6}, {7, 8}}
makeRandomDatas(&data)
}
func makeRandomDatas(dataPoints *[]point) {
for i := 0; i < 10; i++ {
if len(*dataPoints) > 0 {
fmt.Println(makeRandomData(dataPoints))
} else {
fmt.Println("no more elements")
}
}
}
func makeRandomData(cities *[]point) []point {
solution := []point{(*cities)[0]} //create a new slice with the first item from the old slice
*cities = append((*cities)[:0], (*cities)[1:]...) //remove the first item from the old slice
return solution
}https://stackoverflow.com/questions/39993688
复制相似问题