|
1 | 1 | # About |
2 | 2 |
|
3 | | -TODO: add information on pointers concept |
| 3 | +Like many other languages, Go has pointers. |
| 4 | +If you're new to pointers, they can feel a little mysterious but once you get used to them, they're quite straight-forward. |
| 5 | +They're a crucial part of Go, so take some time to really understand them. |
| 6 | + |
| 7 | +Before digging into the details, it's worth understanding the use of pointers. Pointers are a way to share memory with other parts of our program, which is useful for two major reasons: |
| 8 | +1. When we have large amounts of data, making copies to pass between functions is very inefficient. |
| 9 | + By passing the memory location of where the data is stored instead, we can dramatically reduce the resource-footprint of our programs. |
| 10 | +2. By passing pointers between functions, we can access and modify the computer's memory directly, meaning that any changes made by one function are immediately visible to other parts of the program when the function ends. |
| 11 | + |
| 12 | +## Variables and Memory |
| 13 | + |
| 14 | +Let's say we have a regular integer variable `a`: |
| 15 | + |
| 16 | +```go |
| 17 | +var a int |
| 18 | +``` |
| 19 | + |
| 20 | +When we declare a variable, Go has to find a place in memory to store its value. This is largely abstracted from us — when we need to fetch the value stored in that piece of memory, we can just refer to it by the variable name. |
| 21 | + |
| 22 | +For instance, when we write `a + 2`, we are effectively fetching the value stored in the memory associated with the variable `a` and adding 2 to it. |
| 23 | + |
| 24 | +Similarly, when we need to change the value in the piece of memory of `a`, we can use the variable name to do an assignment: |
| 25 | + |
| 26 | +```go |
| 27 | +a = 3 |
| 28 | +``` |
| 29 | + |
| 30 | +The piece of memory that is associated with `a` will now will now be storing the value `3`. |
| 31 | + |
| 32 | +## Pointers |
| 33 | + |
| 34 | +While variables allow us to refer to values in memory, sometimes it's useful to know the **memory address** to which the variable is pointing. **Pointers** hold the memory addresses of those values. You declare a variable with a pointer type by prefixing the underlying type with an asterisk: |
| 35 | + |
| 36 | +```go |
| 37 | +var p *int // 'p' contains the memory address of an integer |
| 38 | +``` |
| 39 | + |
| 40 | +Here we declaring a variable `p` of type "pointer to int" (`*int`). This means that `p` will hold the memory address of an integer. The zero value of pointers is `nil` because a `nil` pointer holds no memory address. |
| 41 | + |
| 42 | +### Getting a pointer to a variable |
| 43 | + |
| 44 | +To find the memory address of the value of a variable, we can use the `&` operator. |
| 45 | +For example, if we want to find and store the memory address of variable `a` in the pointer `p`, we can do the following: |
| 46 | + |
| 47 | +```go |
| 48 | +var a int |
| 49 | +a = 2 |
| 50 | + |
| 51 | +var p *int |
| 52 | +p = &a // the variable 'p' contains the memory address of 'a' |
| 53 | +``` |
| 54 | + |
| 55 | +### Accessing the value via a pointer (dereferencing) |
| 56 | + |
| 57 | +When we have a pointer, we might want to know the value stored in the memory address the pointer represents. We can do this using the `*` operator: |
| 58 | + |
| 59 | +```go |
| 60 | +var a int |
| 61 | +a = 2 |
| 62 | + |
| 63 | +var p *int |
| 64 | +p = &a // the variable 'p' contains the memory address of 'a' |
| 65 | + |
| 66 | +var b int |
| 67 | +b = *p // b == 2 |
| 68 | +``` |
| 69 | + |
| 70 | +The operation `*p` fetches the value stored at the memory address stored in `p`. This operation is often called "dereferencing". |
| 71 | + |
| 72 | +We can also use the derefering operator to assign a new value to the memory address referenced by the pointer: |
| 73 | + |
| 74 | +```go |
| 75 | +var a int |
| 76 | +a = 2 // declare int variable 'a' and assign it the value of 2 |
| 77 | + |
| 78 | +var pa *int |
| 79 | +pa = &a // 'pa' now contains to the memory address of 'a' |
| 80 | +*pa = *pa + 2 // increment by 2 the value at memory address 'pa' |
| 81 | + |
| 82 | +fmt.Println(a) // Output: 4 |
| 83 | + // 'a' will have the new value that was changed via the pointer! |
| 84 | +``` |
| 85 | + |
| 86 | +Assigning to `*pa` will change the value stored at the memory address `pa` holds. Since `pa` holds the memory address of `a`, by assigning to `*pa` we are effectively changing the value of `a`! |
| 87 | + |
| 88 | +A note of caution however: always check if a pointer is not `nil` before dereferencing. Dereferencing a `nil` pointer will make the program crash at runtime! |
| 89 | + |
| 90 | +```go |
| 91 | +var p *int // p is nil initially |
| 92 | +fmt.Println(*p) |
| 93 | +// panic: runtime error: invalid memory address or nil pointer dereference |
| 94 | +``` |
| 95 | + |
| 96 | +### Pointers to structs |
| 97 | + |
| 98 | +So far we've only seen pointers to primitive values. We can also create pointers for structs: |
| 99 | + |
| 100 | +```go |
| 101 | +type Person struct { |
| 102 | + Name string |
| 103 | + Age int |
| 104 | +} |
| 105 | + |
| 106 | +var peter Person |
| 107 | +peter = Person{Name: "Peter", Age: 22} |
| 108 | + |
| 109 | +var p *Person |
| 110 | +p = &peter |
| 111 | +``` |
| 112 | + |
| 113 | +We could have also created a new `Person` and immediately stored a pointer to it: |
| 114 | + |
| 115 | +```go |
| 116 | +var p *Person |
| 117 | +p = &Person{Name: "Peter", Age: 22} |
| 118 | +``` |
| 119 | + |
| 120 | +When we have a pointer to a struct, we don't need to dereference the pointer before accessing one of the fields: |
| 121 | + |
| 122 | +```go |
| 123 | +var p *Person |
| 124 | +p = &Person{Name: "Peter", Age: 22} |
| 125 | + |
| 126 | +fmt.Println(p.Name) // Output: "Peter" |
| 127 | + // Go automatically dereferences 'p' to allow |
| 128 | + // access to the 'Name' field |
| 129 | +``` |
| 130 | + |
| 131 | +## Slices and maps are already pointers |
| 132 | + |
| 133 | +Slices and maps are special types because they already have pointers in their implementation. This means that more often that not, we don't need to create pointers for these types to share the memory address for their values. Imagine we have a function that increments the value of a key in a map: |
| 134 | + |
| 135 | + |
| 136 | +```go |
| 137 | +func incrementPeterAge(m map[string]int){ |
| 138 | + m["Peter"] += 1 |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | +If we create a map and call this function, the changes the function made to the map persist after the function ended. This is a similar behavior we get if we were using a pointer, but note how on this example we are not using any referencing/dereferencing or any of the pointer syntax: |
| 143 | + |
| 144 | +```go |
| 145 | +ages := map[string]int{ |
| 146 | + "Peter": 21 |
| 147 | +} |
| 148 | +incrementPeterAge(ages) |
| 149 | +fmt.Println(ages) |
| 150 | +// Output: map[Peter:22] |
| 151 | +// The changes the function 'addPeterAge' made to the map are visible after the function ends! |
| 152 | +``` |
| 153 | + |
| 154 | +The same applies when changing an existing item in a slice. |
| 155 | + |
| 156 | +However, actions that return a new slice like `append` are a special case and **might not** modify the slice outside of the function. This is due to the way slices work internally, but we won't cover this in detail in this exercise, as this is a more advanced topic. If you are really curious you can read more about this in [Go Blog: Mechanics of 'append'][mechanics-of-append] |
| 157 | + |
| 158 | +## Pointer arithmetic |
| 159 | + |
| 160 | +Unlike other languages, Go does not support pointer arithmetic. This means you cannot go from a memory address of one value to the address of another by incrementing the pointer value. So snippets like the following are invalid: |
| 161 | + |
| 162 | +```go |
| 163 | +var a int |
| 164 | +a = 2 |
| 165 | + |
| 166 | +var pa *int |
| 167 | +pa = &a |
| 168 | +pa++ // NOT ALLOWED: incrementing the pointer or any other pointer arithmetic operations are invalid |
| 169 | +``` |
| 170 | + |
| 171 | +[mechanics-of-append]: https://go.dev/blog/slices |
0 commit comments