Variables

Pointers in Go

A pointer is a variable used to store a memory address.


Syntax
var pointerName *dataType
//accessing a pointer value, or dereferencing
*pointerName

Notes

To access the memory address of any variable (stack included), use the & symbol. This is to reference.

Memory is assigned to pointer variables at runtime and not at compile time. Memory is not directly manipulated, like with stack variables, rather the memory address stores variable's value.

Pointer variables allow the programmer to get the memory address as well as the value. By default, if you were to access the pointer variable as you would a stack variable, you would receive the memory address. This is known as referencing.

To access the value stored at the memory address, add an asterisk. This is known as dereferencing, or indirecting.

Go is garbage collected, so there is no pointer arithmetic.


Example
package main

import "fmt"

func main() {
    animal := "cat"
    var pet *string
    pet = &animal //address of animal now in the pet pointer
    fmt.Println("My pet: ", *pet) //will print cat, value assigned to animal
    *pet = "dog" //assigning a new value to animal's address location, changing its value
    fmt.Println("Type of pet animal: ", animal)
}

See Also
Related

Referencing

Documentation

A Tour of Go

Add to Slack

< Constants   |   Referencing >

© 2018 SyntaxDB. All Rights Reserved.