请教下为啥没添加进去

2022-12-09 00:00:51 +08:00
 ophunter
func testMatrix(res *[][]int) {
   r := *res
   r = append(r, []int{1, 2, 3})
}

fun main(){
   res := make([][]int, 0)
   testMatrix(&res)
   fmt.Println(res)
}

这个 res 为啥是空的 []

1136 次点击
所在节点    Go 编程语言
6 条回复
Mitt
2022-12-09 00:05:50 +08:00
因为 append 会生成新的 slice
Mitt
2022-12-09 00:10:29 +08:00
正确的做法是 *res = append(*res, []int{1, 2, 3})
ophunter
2022-12-09 09:33:04 +08:00
@Mitt 这个 append 生产的新的 slice 地址不是和原来的起始地址一样的原因是吗?
lazydog
2022-12-09 11:02:54 +08:00
你可以打印下地址看看,就知道结果了。
ophunter
2022-12-09 16:02:10 +08:00
@lazydog 谢谢
ophunter
2022-12-09 16:02:14 +08:00
@Mitt 谢谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/901216

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX