Functions receiving references

By default, Go functions receive arguments by value.

But you can pass a reference to a variable to a function. In this case, we need to receive a pointer instead of the value.










func increment(a *int) {
    *a++
}

func main() {
    var a = 1
    increment(&a)
    fmt.Println(a)
}
func main() {
    var a = 1
    var b = &a
    increment(b)
    increment(&a)
    fmt.Println(a)
}









We need to use the * operator to access the value of the pointer.

To get the address of a variable, use the & operator.

We need to use pointers when functions need to modify the value of the argument.










TRY IT OUT

Rob Pike


Exercise: Printing pointer information

Let's try and print the address of the pointer and the value of the pointer in the above code example.