What is pointer?
Programs store values in memory, and each memory block (or word) has an address, which is usually represented as a hexadecimal number, like 0x6b0722
or 0xf84202d7f1
.
Pointer is a special type that holds the address of a variable.
In the above example, variable b has value 157 and is stored at memory address 0x1240a124
.
The variable a
holds the address of b
. Now a
is said to point to b
.
How to create and use pointer
This address can be stored in a special data type called a pointer.
In the above case, it is a pointer to an int.So i1
is denoted by *int
. If we call that pointer intP
, we can declare it as:
1 |
var intP *int |
Go has the address-of operator &
, which, when placed before a
variable, gives us the memory address of that variable.
1 2 3 4 5 6 7 8 9 10 |
package main import "fmt" func main() { a := 10 var p *int = &a fmt.Printf("Type of p is %T\n", p) // prints type *int fmt.Println("Address of a is", p) // prints the address of 0x14000022088 } |
Dereferencing a pointer
Dereferencing a pointer means accessing the value of the variable to which the pointer points.*a
is the syntax to deference a.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package main import "fmt" func main() { i := 10 var p *int = &i *p = 20 // changing the value at &i fmt.Printf("Here is the pointer p: %p\n", p) // prints address fmt.Printf("Here is the *p: %d\n", *p) // prints integer fmt.Printf("Here is the new value of i: %d\n", i) // prints the same integer } |
What you can’t do with golang pointers
Go has the concept of pointers like most other low level languages – C, C++.
But it’s not allowed to do calculations with pointers.
This often lead to erroneous memory access in C or C++ and thus fatal crashes of programs.
This restrictions with pointers in Go makes the language memory-safe.