Skip to content

Instantly share code, notes, and snippets.

@hayeah
Created May 26, 2014 12:02
Show Gist options
  • Save hayeah/46c36c10ef662a96e25c to your computer and use it in GitHub Desktop.
Save hayeah/46c36c10ef662a96e25c to your computer and use it in GitHub Desktop.
Golang go Pointer Gotcha
package main
import (
"fmt"
"time"
)
type foo struct {
i int
}
func (f *foo) bar(tag string) {
fmt.Printf("%v: %v\n", tag, f)
}
func main() {
fs := []foo{
{i: 1},
{i: 2},
}
for _, f := range fs {
// go resolves the parameters. Because the bar method expects pointer
// type, it is resolved to the address of the loop variable.
// wrong
go f.bar("1")
// go (&f).bar("1") // same as above
// ok
// go fs[i].bar("1")
// ok. This works because f2 is a fresh copy of f in a new memory address
// f2 := f
// go f2.bar("1")
}
fs2 := []*foo{
{i: 1},
{i: 2},
}
for _, f := range fs2 {
// ok. f is a pointer
go f.bar("2")
}
time.Sleep(1 * time.Second)
}
// Output:
// 1: &{2}
// 1: &{2}
// 2: &{1}
// 2: &{2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment