Go - Pointer

About

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.

Properties

• 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.

Operator

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

Powered by ComboStrap