Pointers in Go (Golang)

A pointer is a variable that stores the memory address of another variable. In Go, pointer types look like *int, *string, *MyStruct, etc.

  • &x → “address of x”
  • *p → “value at the address stored in p” (dereference)

Why pointers are used

Pointers are useful when you want:

  • To modify a variable inside a function (pass-by-reference style)
  • To avoid copying large structs (performance)
  • To share one piece of data across multiple functions safely (with proper synchronization)

Basic pointer example (address + dereference)

package main

import "fmt"

func main() {
    num := 60
    ptr := &num // ptr stores address of num

    fmt.Println("num:", num)
    fmt.Println("&num:", &num)
    fmt.Println("ptr:", ptr)
    fmt.Println("*ptr:", *ptr) // dereference

    *ptr = 90 // modify through pointer
    fmt.Println("updated num:", num)
}

Nil pointer

Uninitialized pointers are nil.

var p *int
fmt.Println(p) // <nil>

You must not dereference nil (*p) — it will panic.


Passing pointers to functions (modify original)

Method 1: Pass a pointer variable

func modifyValue(p *int) {
    *p = 1234
}

func main() {
    num := 42
    ptr := &num
    modifyValue(ptr)
    fmt.Println(num) // 1234
}

Method 2: Pass address directly

modifyValue(&num)

Pointers with structs

Using & (address of an existing struct)

type Book struct {
    title  string
    author string
}

func main() {
    b := Book{title: "Go Programming", author: "Alice"}
    pb := &b

    pb.title = "Advanced Go" // auto-dereference for fields
    fmt.Println(b.title)     // Advanced Go
}

Using new

new(T) allocates zero-value T and returns *T.

type Car struct {
    model string
    year  int
}

func main() {
    pc := new(Car)
    pc.model = "Tesla Model 3"
    pc.year = 2023
}

Pointer to pointer (**T) — “double pointer”

A pointer can also point to another pointer.

package main

import "fmt"

func main() {
    number := 500
    p1 := &number
    p2 := &p1 // pointer to pointer

    fmt.Println(number) // 500
    fmt.Println(*p1)    // 500
    fmt.Println(**p2)   // 500

    **p2 = 1000
    fmt.Println(number) // 1000
}

Comparing pointers

You can compare pointers using == and !=.

  • Two pointers are equal if they point to the same address, or both are nil.

✅ Correct comparison (compare pointer values):

p1 := &a
p2 := &b
p3 := &a

fmt.Println(p1 == p2) // false
fmt.Println(p1 == p3) // true

⚠️ Note: comparing &p1 == &p2 compares the addresses of the pointer variables themselves, not what they point to.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *