CodeNebula
Go🔧Core Languagebeginner

Pointers

Go · Core Language · Run with go run

Explanation

Go has pointers but no pointer arithmetic. A pointer holds the memory address of a value. Use `&` to take an address, `*` to dereference. Pointers are primarily used for: mutating a value through a function argument, sharing large structs without copying, and expressing optional values (nil pointer = absent).

Real-World Scenario

A configuration parser populates a struct via a pointer parameter: `func Parse(cfg *Config) error`. The caller allocates the struct and passes its address, and the parser fills it in place — no copy overhead.

Quick Snippet

snippet.go
x := 10
p := &x       // p is *int, holds address of x
*p = 20       // dereference: x is now 20
fmt.Println(x) // 20

// nil pointer — optional value pattern
type Node struct {
    Value int
    Next  *Node // nil when there is no next node
}

Full Example

pointers.go
// Compile: go run pointers.go
// Output:
//   before: 10
//   after:  20
//   list: 1 -> 2 -> 3 -> nil
package main

import "fmt"

type Node struct {
	Value int
	Next  *Node
}

func main() {
	x := 10
	p := &x // p is *int, holds address of x
	fmt.Println("before:", x)
	*p = 20 // dereference and assign
	fmt.Println("after: ", x)

	// nil pointer terminates a linked list
	list := &Node{Value: 1, Next: &Node{Value: 2, Next: &Node{Value: 3}}}
	fmt.Print("list: ")
	for n := list; n != nil; n = n.Next {
		fmt.Printf("%d -> ", n.Value)
	}
	fmt.Println("nil")
}
Run command
go run pointers.go