Go: Pointers explained

A pointer is a vari­able that con­tains the address of an object.

Basics

Structs and arrays are copied when used in assignments and passed as arguments to functions. With pointers this can be avoided.

Pointers store addresses of objects, which can be passed around efficiently, rather than actual objects:

type Person struct {
        Name string
}

var pp *Person = new(Person) // pp holds the address of the new struct

The variable declaration can be written more compactly:

pp := new(Person)

Address operator

To get the address of an object, use the & operator like this:

p := Person{"Alice"} // p holds the actual struct 
pp := &p             // pp holds the address of the struct 

The & operator can also be used with composite literals. The above two lines can be written as:

pp := &Person{"Alice"}

Pointer indirection

For a pointer x, the pointer indirection *x denotes the value which x points to. Pointer indirection is rarely used, since Go can automatically take the address of a variable:

pp := new(Person)
pp.Name = "Alice" // same as (*pp).Name = "Alice"

Pointers as parameters

When using a pointer to modify an object, you're affecting everybody that uses that object.

// Bob is a function that has no effect.
func Bob(p Person) {
        p.Name = "Bob" // changes only the local copy
}

// Charlie sets pp.Name to "Charlie".
func Charlie(pp *Person) {
        pp.Name = "Charlie"
}

func main() {
        p := Person{"Alice"}

        Bob(p)
        fmt.Println(p) // prints {Alice}

        Charlie(&p)
        fmt.Println(p) // prints {Charlie}
}

Comments

Be the first to comment!