Pointers (Memory Addresses & Dereferencing) - Go Tutorial for Beginners #14
Video: Pointers (Memory Addresses & Dereferencing) - Go Tutorial for Beginners #14 by Taught by Celeste AI - AI Coding Coach
Watch full page →Pointers (Memory Addresses & Dereferencing) in Go
Pointers in Go allow you to work directly with memory addresses, enabling efficient manipulation of variable values. This tutorial covers the basics of pointers, including how to obtain addresses, dereference pointers to access or modify values, and use pointers in functions for pass-by-reference behavior.
Code
package main
import "fmt"
func main() {
// Address-of and dereference
x := 42
p := &x // p holds the address of x
fmt.Println(*p) // dereference p to get value of x, prints 42
// Modify value via pointer
*p = 100 // changes x to 100
fmt.Println(x) // prints 100
// Pass by value - original not changed
num := 10
doubleValue(num)
fmt.Println(num) // prints 10
// Pass by pointer - original changed
doublePointer(&num)
fmt.Println(num) // prints 20
// Nil pointer safety check
var ptr *int // ptr is nil
if ptr != nil {
fmt.Println(*ptr) // safe to dereference only if not nil
} else {
fmt.Println("ptr is nil, cannot dereference")
}
}
// Function that doubles value - does not affect original
func doubleValue(n int) {
n = n * 2
}
// Function that doubles value via pointer - modifies original
func doublePointer(n *int) {
*n = *n * 2
}
Key Points
- Pointers store the memory address of a variable, accessed using the & operator.
- The * operator dereferences a pointer to read or modify the value it points to.
- Passing a pointer to a function allows the function to modify the original variable.
- Always check for nil pointers before dereferencing to avoid runtime errors.
- Go does not support pointer arithmetic, promoting safer memory access.