Dereferencing

Dereferencing is the act of accessing the value located at the memory address stored in a pointer.

The * Operator

While * is used to declare a pointer type, it is also used as an operator to dereference a pointer.

x := 42
p := &x

fmt.Println(*p) // read x through p (42)
*p = 21         // set x through p
fmt.Println(x)  // x is now 21

Safety: Nil Checks

Dereferencing a nil pointer will cause a runtime panic, which crashes your program. Always check if a pointer is nil before dereferencing it if there’s any chance it might be empty.

if p != nil {
    fmt.Println(*p)
}

Pointer Arithmetic

Unlike languages like C, Go does not allow pointer arithmetic (e.g., p++ to move to the next memory address). This design choice makes Go significantly safer and prevents many common memory-related bugs.