Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Golang Gotchas: 2D slice #14

Open
wisecsj opened this issue Feb 4, 2019 · 1 comment
Open

Golang Gotchas: 2D slice #14

wisecsj opened this issue Feb 4, 2019 · 1 comment

Comments

@wisecsj
Copy link
Owner

wisecsj commented Feb 4, 2019

rlt := make([][]int,0)
tmp := make([]int,5)

rlt = append(rlt,tmp)

如上,在某个函数里,对tmp进行更改(不超过cap),然后把一维切片tmp append 到rlt。

如果你打印rlt,最后你会发现所有一维切片的数据都是一样的。

因为slice其实是SliceHeader,内部引用的是一个数组。

所以,你每次调用函数实际上是对同一个数组里的值进行修改。

而rlt存储的又是一维切片(对数组指针的包装),所以造成最后所有的值都一样。

@wisecsj
Copy link
Owner Author

wisecsj commented Feb 4, 2019

正确的做法:

make一个与tmp大小一样的切片B,然后copy过去,append切片B到rlt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant