Go - Pointer

Card Puncher Data Processing


Data Type - Pointer (Locator) in Go

In Go, Pointers are explicitly visible.

  • The & operator yields the address of a variable,
  • and the * operator retrieves the variable that the pointer refers to

but there is no pointer arithmetic.


  • The zero value for a pointer of any type is nil.
  • The test p != nil is true if p points to a variable.
  • Pointers are comparable; two pointers are equal if and only if they point to the same variable or both are nil.


The address operator (&)

If a variable is declared var x int

var x int := 1;

The below expression &x (pronounced address of x) yields a pointer to the integer variable, that is, a value of type *int, which is pronounced pointer to int

p := &x // p, of type *int, points to x

We say:

  • p points to x
  • or equivalently p contains the address of x

Expressions that denote variables are the only expressions to which the address-of operator & may be applied.

Let op ! Each call of f returns a distinct value. See Go - Alias

func f() *int { 
    v := 1
    return &v 

fmt.Println( f() = = f()) // "false"

The variable operator (*p)

The variable to which p points is written *p. The expression *p yields the value of that variable, an int.

fmt.Println(*p) // "1" 

Since *p denotes a variable, it may also appear on the left-hand side of an assignment, in which case the assignment updates the variable.

*p = 2 // equivalent to x = 2 
fmt.Println(x) // "2"

Documentation / Reference

Discover More
Card Puncher Data Processing
Go - New

The expression new(T): creates an unnamed variable of type T, initializes it to the zero value of T, and returns its address, which is a value of type T. new is a predeclared function, not a...
Card Puncher Data Processing
Go - Reference Type

Reference type in go , , , ,
Card Puncher Data Processing
Go - Type

in Go the rules are simple: the assignment types must exactly match, and nil may be assigned to any variable of interface or reference type. Type declarations most often appear at package...

Share this page:
Follow us:
Task Runner