Last active
September 2, 2018 17:25
-
-
Save ehernandez-xk/220a0c0c5ea45bfcc55fd87b43c52803 to your computer and use it in GitHub Desktop.
for loop with pointer, a gotcha
This file contains 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
// Here an example of deep understanding of an unexpected output when use pointers in a loop | |
// test2 it is clear to understand than test1 | |
// test1 and test2 are equivalent | |
package main | |
import ( | |
"fmt" | |
) | |
type p struct { | |
name string | |
} | |
func test1() { | |
ps := []p{ | |
{"A"}, | |
{"B"}, | |
{"C"}, | |
} | |
px := []*p{} | |
for _, value := range ps { | |
px = append(px, &value) | |
} | |
fmt.Println(ps[0], ps[1], ps[2]) | |
fmt.Println(px[0], px[1], px[2]) | |
} | |
func test2() { | |
ps := []p{ | |
{"A"}, | |
{"B"}, | |
{"C"}, | |
} | |
px := []*p{} | |
var value p | |
for i := 0; i < len(ps); i++ { | |
value = ps[i] | |
px = append(px, &value) | |
} | |
fmt.Println(ps[0], ps[1], ps[2]) | |
fmt.Println(px[0], px[1], px[2]) | |
} | |
func main() { | |
test1() | |
test2() | |
/* | |
{A} {B} {C} | |
&{C} &{C} &{C} | |
{A} {B} {C} | |
&{C} &{C} &{C} | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment