Pointers in Golang
A pointer holds a variable’s address in the computer’s memory. One can say that once a pointer is created, its value is just an address that lead you to where in the computer’s memory the program will store the actual data.
Example
1package main
2
3import "fmt"
4
5func main() {
6
7 // Creating a pointer
8 var fullNamePtr *string = new(string)
9 fmt.Println(fullNamePtr) // Prints the address: 0x14000110230
10
11 // Storing value in the pointer's address by dereferencing it
12 *fullNamePtr = "John Doe"
13 fmt.Println(fullNamePtr, *fullNamePtr)
14
15 // Getting the pointer of an existing variable
16 country := "Brazil"
17 fmt.Println(&country)
18}
When to use pointers
Since I come from the Javascript world, despite learning the syntax to create a pointer, learning when to use them wasn’t that obvious.
For instance, in Javascript, it is possible to mutate a property from literal object inside a function by just updating the argument passed:
1const person = {
2 name: "John Doe",
3};
4
5function updateName(person, name) {
6 person.name = name;
7}
8
9updateName(person, "Jane Smith");
10
11console.log(person); // { name: "Jane Smith" }
In Go, such operation wouldn’t mutate the struct passed as argument, unless the function updateName
was declared with an interface ready to receive a pointer, rather than an actual value.
1package main
2
3import (
4 "fmt"
5)
6
7type Person struct {
8 Name string
9}
10
11func updatePersonName(person *Person, name string) {
12 person.Name = name
13}
14
15func main() {
16 fmt.Println("Go fundamentals")
17
18 person := Person{Name: "John Doe"}
19
20 fmt.Println(person) // {John Doe}
21
22 updatePersonName(&person, "Jane Smith")
23
24 fmt.Println(person) // {Jane Smith}
25}