Go Data Type Pointers

Introduction

Pointers reference a location in memory where a value is stored rather than the value itself.

* and & operators

In Go, a pointer is represented using an asterisk (*) followed by the type of the stored value.

An asterisk is also used to dereference pointer variables.

Dereferencing a pointer returns the value the pointer points to.

*xPtr=0 means store the int 0 in the memory location xPtr refers to.

We use the & operator to find the address of a variable.

&x returns a *int (pointer to an int) because x is an int.

This is what allows us to modify the original variable.

When we call a function that takes an argument, that argument is copied to the function:

package main//  w w w  .  j  a v a  2  s. co m

import "fmt"
func zero(xPtr *int) { 
    *xPtr = 0 
} 
func main() { 
    x  := 5 
    zero(&x) 
    fmt.Println(x) // x is 0 
} 

By using a pointer (*int), the zero function is able to modify the original variable.

&x in main and xPtr in zero refer to the same memory location.




PreviousNext

Related