Mastodon hachyterm.io

Declaration and Assignment

Go is statically typed. Before you can bind a variable, you have to declare it:

var age int

This declares a new variable called age of type Integer. The variable is declared, but not initialized.

If you want to assign something to a variable, you’ll do it like this:

age = 35

There is a short-hand operator: :=:

age := 35

The “walrus operator” is syntactic sugar for the two commands:

var age int
age = 35

Asterisk and Ampersand

Go has two syntactic constructs that are unclear to newcomers: the asterisk (*) and the ampersand (&).

Go has pointers. Pointers reference a location in memory where a variable is stored.

The asterisk (* operator) is used for dereferencing the pointer location.

From A Tour of Go:

fmt.Println(*p) // read i through the pointer p
*p = 21         // set i through the pointer p

The ampersand (& operator) generates a pointer to its operant:

age := 35        // stores the value
agePointer &age // stores the pointer address (reference)

Further Reading