26. Pointers
Sharing!
Pointers
Pointers is is type of variable in Go. Instead of string a value type, pointer stores address of another variable. Pointer points to address of another variable in Go. To get address of variable, we use &
operator. To get value that pointer points to, we use *
operator.
Pointer Type
Like we can declare variables to hold different types of values in Go, we can also declare pointer that holds address of different Go types. Variable intP
is pointer to int
type while floatP
is pointer to float64
type. Similar to value types, we can not assign pointer of type X to pointer of type Y.
Pointer to structure
It is common to use Pointers with struct in Go. Since it is common use case, for de-referencing (getting value out of pointer) Go does not require us to use asterisk (*)
symbol. Instead of (*myLocation).street
we can use myLocation.street
Sharing Data
Main use of pointers is to share data between function calls. Pointers when used efficiently help us increase system performance by sharing data instead of making a fresh copy every time between function calls. updateLocation
function accepts pointer to location
type and it can update myLocation
variable value using pointer.
Blog Resources
Last updated