Go lang 地址、指针和类型:
s := "hello" // type string
t := "bye" // type string
u := 44 // type int
v := [2]int{1, 2} // type array
q := &s // type pointer
所有这些Go 变量都有一个address in memory。它们之间的区别是字符串类型保存字符串值,int 类型保存整数值,指针类型保存地址。所以即使是保存地址的变量也有自己的内存地址。
指针:
在变量名计算其地址之前添加&。或者想,“这是我的地址,所以你知道在哪里可以找到我。”
// make p type pointer (to string only) and assign value to address of s
var p *string = &s // type *string
// or
q := &s // shorthand, same deal
在指针变量取消引用指向它所持有地址的指针之前添加*。或者想一想,“将操作传递给我的价值地址。”
*p = "ciao" // change s, not p, the value of p remains the address of s
// j := *s // error, s is not a pointer type, no address to redirect action to
// p = "ciao" // error, can't change to type string
p = &t // change p, now points to address of t
//p = &u // error, can't change to type *int
// make r type pointer (to a pointer which is a pointer to a string) and assign value to address of p
var r **string = &p // shorthand: r := &p
w := ( r == &p) // ( r evaluates to address of p) w = true
w = ( *r == p ) // ( *r evaluates to value of p [address of t]) w = true
w = (**r == t ) // (**r evaluates to value of t) w = true
// make n type pointer (to string) and assign value to address of t (deref'd p)
n := &*p
o := *&t // meaningless flip-flop, same as: o := t
// point y to array v
y := &v
z := (*y)[0] // dereference y, get first value of element, assign to z (z == 1)
去这里玩吧:http://play.golang.org/p/u3sPpYLfz7