Friday 13 May 2016

Pointers in Golang

Go has pointers. A pointer holds the memory address of a variable.
The type *T is a pointer to a T value. Its zero value is nil.
var p *int
fmt.Println(p)
<nil>
fmt.Println(*p)
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x0 pc=0x401771]
The empty pointer points to nil

The & operator generates a pointer to its operand. &i is a pointer,
i := 42
p = &i
fmt.Println(&i)
0xc0820022b8
The * operator denotes the pointer's underlying value.
fmt.Println(*p) // read i through the pointer p
42
*p = 21        // set i through the pointer p, 
               //the value in p's address changes from 42 to 21
This is known as "dereferencing" or "indirecting".

v := Vertex{1, 2}
p := &v
(*p).X = 10
fmt.Println(&v)
&{10 2}
To access the field X of a struct when we have the struct pointer p,we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.

Unlike C, Go has no pointer arithmetic.

No comments:

Post a Comment