Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).
Before we start there are two important operators which we will use in pointers i.e.
* Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address.
& operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer.
Declaring a pointer:
var pointer_name *Data_Type
Example: Below is a pointer of type string which can store only the memory addresses of string variables.
var s *string
Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example:
// normal variable declaration var a = 45 // Initialization of pointer s with // memory address of variable a var s *int = &a
Example: In the following example, using pointer we will access the value of the variable whose address is stored in pointer.
Address of the variable: 0xc00010a040 Address stored in the pointer variable: 0xc00010a040 Value of the Actual Variable: Geeks For Geeks Value of the Pointer variable: Geeks For Geeks
Explanation: Here (&) symbol is used to get the address of the variable storing the value as “Geeks for Geeks”. The address owned by this variable is the same which is stored in the pointer. Therefore, the output of &dummyVar and pointerVariable is the same. To access the value stored at the address, which is stored in pointer we user (*) symbol.