Skip to content

Instantly share code, notes, and snippets.

@tenntenn
Created October 5, 2012 01:34
Show Gist options
  • Save tenntenn/3837557 to your computer and use it in GitHub Desktop.
Save tenntenn/3837557 to your computer and use it in GitHub Desktop.
Tip for golang recievers
// http://play.golang.org/p/TC1PoskmV2
package main
import "fmt"
type Foo struct {
n int
}
func (foo Foo) String() string {
return fmt.Sprintf("&f == &foo is %v, foo.n = %d", &f == &foo, foo.n)
}
type Bar struct {
m int
}
func (bar *Bar) String() string {
if bar == nil {
return "bar is nil"
}
return fmt.Sprintf("&b == &bar is %v, bar.m = %d", &b == bar, bar.m)
}
var f Foo
var b Bar
func main() {
// Foo
fmt.Println("foo1:", f) // foo1
f.n = 100
fmt.Println("foo2:", f) // foo2
// Pointer of Foo
var fp *Foo
fmt.Println("foo3:", fp) // foo3
fp = &f
fmt.Println("foo4:", fp) // foo4
fmt.Println()
// Bar
fmt.Println("bar1:", b) // bar1
b.m = 200
fmt.Println("bar2:", b) // bar2
// Pointer of Bar
var bp *Bar
fmt.Println("bar3:", bp) // bar3
bp = &b
fmt.Println("bar4:", bp) // bar4
}
@tenntenn
Copy link
Author

tenntenn commented Oct 5, 2012

foo1: &f == &foo is false, foo.n = 0
foo2: &f == &foo is false, foo.n = 100
foo3:
foo4: &f == &foo is false, foo.n = 100

bar1: {0}
bar2: {200}
bar3: bar is nil
bar4: &b == &bar is true, bar.m = 200

@tenntenn
Copy link
Author

tenntenn commented Oct 5, 2012

foo1: &f == &foo is false, foo.n = 0
foo2: &f == &foo is false, foo.n = 100
foo3: <nil>
foo4: &f == &foo is false, foo.n = 100

bar1: {0}
bar2: {200}
bar3: bar is nil
bar4: &b == &bar is true, bar.m = 200

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment