The Go language supports pointers—with a pointer, we store an address of a variable. We can then use the pointer to get the variable's value.
To get the value of a variable from a pointer, we use the pointer indirection (star) operator. To create a pointer, we use the address operator.
This example uses a pointer to a string
in a struct
. Because Go has garbage collection, we can use pointers to variables without worrying about when to free variables from memory.
string
pointer in a struct
. The pointer is a value that stores the address of a string
variable.func
can receive a pointer. To get the value from the pointer, we use the "*" pointer indirection operator.struct
that has a pointer within it. We use the address operator to set the value of the pointer field "x".Println
, we see that the pointer holds an address value. When we use the "*" operator we see the actual string
value.package main import "fmt" // Part 1: use a pointer to string as a field in a struct. type Test struct { x *string } func Example(x *string) { // Part 2: receive a pointer as an argument, and access its value with pointer indirection. fmt.Println("func Example", *x) } func main() { // Part 3: create a string, and use the address operator to initialize a pointer in a struct. v := "bird" t := Test{x: &v} // Part 4: print the address of the string pointer, and also its value. fmt.Println(" t", t) fmt.Println(" t.x", t.x) fmt.Println("*t.x", *t.x) // Part 5: pass a string pointer to a method. Example(&v) Example(t.x) } t {0xc0000220a0} t.x 0xc0000220a0 *t.x bird func Example bird func Example bird
Go supports pointers, but because it has garbage collection, we do not need to worry about the pointers becoming invalid or being freed from memory when they are still needed.
The syntax for Go pointers is similar to (or the same as) languages like C. We cannot use arithmetic on pointers, as this would not work well with the garbage collector.