capypad
0 day streak
go / beginner
Snippet

Pointers and Memory Addresses

Pointers hold memory addresses instead of values. The `&` operator gets a pointer to a variable, while `*` dereferences a pointer to access the value. In `double`, the `*int` parameter expects a pointer, allowing mutation of the original variable. The zero value of a pointer is `nil`, and you should always check before dereferencing.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main
 
import "fmt"
 
func double(n *int) {
*n = *n * 2
}
 
func main() {
value := 21
fmt.Printf("Before: %d\n", value)
 
double(&value)
fmt.Printf("After: %d\n", value)
 
var ptr *int = &value
fmt.Printf("Address: %p, Value: %d\n", ptr, *ptr)
 
if ptr != nil {
fmt.Println("Pointer is not nil")
}
}
Breakdown
1
func double(n *int) {
Function takes a pointer to int
2
*n = *n * 2
Dereferences and modifies the original value
3
double(&value)
Passes address of value using & operator
4
var ptr *int = &value
Declares pointer variable explicitly
5
if ptr != nil {
Always check if pointer is not nil before use