You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This bug can be reproduced by executing this small script
package main
import "fmt"
type A struct {
a,b int
}
func main() {
var a []A
for i := 0; i < 5; i++ {
a = append(a, A{a:i,b:i+1})
}
fmt.Println(a)
var b []*A
for _, v := range a {
b = append(b, &v)
}
fmt.Println(b)
for _, v := range b {
fmt.Println(v)
}
}
What did you expect to see?
I expect to have the same list of values I have i the variable a even in the variable b just that in b I will have pointers to the values.
The output that I would expect should look like this:
for i := 0; i < len(a); i++ {
b = append(b, &a[i])
}
are not the same. In the latter, you are taking the address of element a[i] in the array (which is what you want). In the former, you are taking the address of the iteration variable v, which, as you discovered, does not change during the loop execution (it gets allocated once, it's in a completely new location in memory, and gets overwritten at each iteration).
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes it can be reproduced with the last version ( 1.9 )
What operating system and processor architecture are you using (
go env
)?What did you do?
This bug can be reproduced by executing this small script
What did you expect to see?
I expect to have the same list of values I have i the variable a even in the variable b just that in b I will have pointers to the values.
The output that I would expect should look like this:
What did you see instead?
This is the output i got:
All pointers in the new slice point to the same value that is the last value of the previous slice
The text was updated successfully, but these errors were encountered: