我对 Go 中的按值传递感到困惑。我正在这样做;package mainimport ( "fmt")type point struct { x int list []int}func main() { p := point{20, []int{1, 2, 3, 4, 5}} fmt.Printf("Address: %p, Value: %v\n", &p, p) passByValue(p, 1) fmt.Printf("Address: %p, Value: %v\n", &p, p)}func passByValue(copyOfP point, i int) { copyOfP.list = append(copyOfP.list[:i], copyOfP.list[i+1:]...) fmt.Printf("From passByValue Address: %p, Value: %v\n", ©OfP, copyOfP)}输出:Original p Address: 0xc00000c080, Value: {20 [1 2 3 4 5]}passByValue copyOfP Address: 0xc00000c0c0, Value: {20 [1 3 4 5]}Original p Address: 0xc00000c080, Value: {20 [1 3 4 5 5]}不copyOfP应该是副本,p也不应该反映原来p的东西。这里发生了什么事?
1 回答
神不在的星期二
TA贡献1963条经验 获得超6个赞
func main() {
// history.ReadlineTest()
p := point{20, []int{1, 2, 3, 4, 5}}
fmt.Printf("Address: %p, Value: %v\n", &p.list[0], p)
passByValue(p, 1)
fmt.Printf("Address: %p, Value: %v\n", &p.list[0], p)
}
func passByValue(copyOfP point, i int) {
copyOfP.list = append(copyOfP.list[:i], copyOfP.list[i+1:]...)
fmt.Printf("From passByValue Address: %p, Value: %v\n", ©OfP.list[0], copyOfP)
}
Address: 0xc00001a0c0, Value: {20 [1 2 3 4 5]}
From passByValue Address: 0xc00001a0c0, Value: {20 [1 3 4 5]}
Address: 0xc00001a0c0, Value: {20 [1 3 4 5 5]}
“列表”切片重用了相同的内存。
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报
0/150
提交
取消