Pointers in Go

Feb. 10, 2022, 7:38 p.m.

Pointer is a data type in Go. It shows the address of a value. The pointer type is also called the reference type.

Example of a pointer: 0xc000126000. This is an address in a memory location.

Reference a value

Normally, we work with some value types such as integer or string. In order to get the pointer or the reference of that value, we can place the & keyword before the variable name to refer to its memory location. Or in other words, we use & to get the pointer of that value.

The syntax &variableName:

a := 111
fmt.Println(&a)

This code prints out 0xc00010a000, which is the memory location of a, not the value of a (111)

Type of pointers

The type of pointers will be displayed with the * before the value type. Example: *int, *string.

a := 111
fmt.Printf("%T", &a)

fmt.Println()

b := "Hello"
fmt.Printf("%T", &b)

This will print out

*int
*string

Dereference a pointer

When we have a pointer and want to get its value, we place the * before that pointer.

a := 111
fmt.Println(&a)
fmt.Println(*&a)

c := &a
fmt.Println(c)
fmt.Println(*c)

It prints out

0xc000126000
111
0xc000126000
111

Change the value held by a pointer

When we have a pointer, we can change the value it is holding by dereferencing it.

a := 111
fmt.Println(a)

c := &a
*c = 222
fmt.Println(a)

The result is:

111
222