Last active
September 5, 2020 02:18
-
-
Save manhdaovan/9dc7e50b5b241f97734670178c7bfcc8 to your computer and use it in GitHub Desktop.
Annoying scope variable in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type A struct { | |
val int | |
} | |
type B struct { | |
a *A | |
} | |
func main() { | |
fmt.Println("Hello, playground") | |
as := []A{A{0}, A{1}, A{2}, A{3}, A{4}} | |
bs := make([]B, 0, len(as)) | |
for _, a := range as { | |
// a := a // scope for fixing this annoying | |
fmt.Printf("pointer = %p \n", &a) | |
bs = append(bs, B{&a}) | |
} | |
for i, b := range bs { | |
fmt.Println("i = ", i, "b = ", b, "b.a.val = ", b.a.val) | |
} | |
} | |
Hello, playground | |
pointer = 0x40e020 | |
pointer = 0x40e020 | |
pointer = 0x40e020 | |
pointer = 0x40e020 | |
pointer = 0x40e020 | |
i = 0 b = {0x40e020} b.a.val = 4 | |
i = 1 b = {0x40e020} b.a.val = 4 | |
i = 2 b = {0x40e020} b.a.val = 4 | |
i = 3 b = {0x40e020} b.a.val = 4 | |
i = 4 b = {0x40e020} b.a.val = 4 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment