Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A pointer in Go is a variable that stores the memory address of another variable, rather than storing the actual data value itself. Pointers provide a mechanism for indirect memory access and mutation of the underlying data structure.

Core Operators

Go utilizes two primary operators for pointer manipulation:
  • & (Address-of Operator): Retrieves the memory address of a variable.
  • * (Indirection/Dereference Operator): Accesses or mutates the value stored at the memory address the pointer holds. When used in a type declaration (e.g., *int), it denotes a pointer type.

Declaration and Initialization

A pointer is strictly typed to the data it points to. An uninitialized pointer has a zero value of nil.
// Declaration without initialization (evaluates to nil)
var p *int 

// Initialization using the address-of operator
value := 42
p = &value 

// Initialization using the built-in new() function
// new() allocates zeroed storage for the specified type and returns a pointer to it
ptr := new(int) 

Dereferencing and Mutation

To read or modify the underlying data a pointer references, you must dereference it using the * operator.
package main

import "fmt"

func main() {
    x := 10
    
    // p is of type *int, pointing to x
    p := &x 
    
    // Reading through the pointer (Dereferencing)
    fmt.Println(p)  // Output: 0xc00001a0b8 (Memory address representation)
    fmt.Println(*p) // Output: 10 (Value at the address)
    
    // Mutating through the pointer
    *p = 21 
    
    // The underlying variable is modified
    fmt.Println(x)  // Output: 21
}

Struct Pointers and Automatic Dereferencing

When working with pointers to structs, Go provides syntactic sugar. You do not need to explicitly dereference the pointer to access the struct’s fields. Go handles the indirection automatically.
package main

type Vertex struct {
    X, Y int
}

func main() {
    v := Vertex{1, 2}
    p := &v
    
    // Explicit dereferencing (valid, but unidiomatic)
    (*p).X = 10 
    
    // Implicit dereferencing (idiomatic Go)
    p.Y = 20 
}

Language Constraints

  • No Pointer Arithmetic: Unlike C or C++, Go does not natively support pointer arithmetic (e.g., p++ or p + 4 is invalid). This restriction ensures memory safety and simplifies garbage collection. To perform pointer arithmetic, developers must explicitly bypass the type system using the unsafe package.
  • Strict Type Safety: A pointer of type *int cannot be assigned the address of a float64 variable.
  • Nil Pointer Dereference: Attempting to dereference a pointer that evaluates to nil will result in a fatal runtime panic.
Master Go with Deep Grasping Methodology!Learn More