Sometimes I confuse how to retrieve from pointer variable. So I wanna summary the pointer of Golang not to forget them.
Because I haven't used languages which have pointer variable.
Then it's just memo for me.
- & stands for the memory address of value.
- * (in front of values) stands for the pointer's underlying value
- * (in front of types name) stands for to store an address of another variable
It's an example
package main
import "fmt"
type H struct {
id *int
}
func main() {
a := 10
p := &a
fmt.Println(p) //0x10410020
fmt.Println(*p) //10
a = 11
fmt.Println(p) //0x10410020
fmt.Println(*p)
q := 90
b := H{id: &q}
fmt.Println(b.id) //0x1041002c
fmt.Println(*b.id) //90
q = 80
fmt.Println(b.id) //0x1041002c
fmt.Println(*b.id) //80
}
Top comments (4)
Another way to get a pointer is to use the built-in new function:
new takes a type as an argument, allocates enough memory to fit a value of that type and returns a pointer to it.
Concise and easy to understand summary, thank you for sharing :)
play.golang.org/p/YI6-As7AhZ
Thank you so much my friend. This is exactly what I needed.