Sukma Rizki
Posted on March 2, 2024
Variables in Golang using pointers are marked with *(asterisk) right before writing the data type
var number *int
var name *string
The default value of a pointer variable is nil (empty). A pointer variable cannot hold a value that is not a pointer, and vice versa, an ordinary variable cannot hold a pointer value.
Let's just put it into practice
var numberA int = 4
var numberB *int = &numberA
fmt.Println("numberA (value) :", numberA) // 4
fmt.Println("numberA (address) :", &numberA) // 0xc20800a220
fmt.Println("numberB (value) :", *numberB) // 4
fmt.Println("numberB (address) :", numberB) // 0xc20800a220
The variable numberB is declared as an int pointer with an initial value of
variable reference numberA (can be seen in the code &numberA ). With this,
variables numberA and numberB hold data with address references
the same memory.
If printed, a pointer variable will produce a memory address string (in
hexadecimal notation), for example numberB which is printed produces
0xc20800a220 .
The original value of a pointer variable can be obtained by dereference
first (can be seen in the code *numberB ).
Posted on March 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.