Skip to content

Instantly share code, notes, and snippets.

@ehernandez-xk
Last active September 2, 2018 17:25
Show Gist options
  • Save ehernandez-xk/220a0c0c5ea45bfcc55fd87b43c52803 to your computer and use it in GitHub Desktop.
Save ehernandez-xk/220a0c0c5ea45bfcc55fd87b43c52803 to your computer and use it in GitHub Desktop.
for loop with pointer, a gotcha
// 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