</>
Skip to content
Go lessons (21/34)

Go — Pointers

What is a pointer

package main

import "fmt"

func main() {
    x := 10
    p := &x    // p is *int

    fmt.Println(*p)  // 10 (dereference)
    *p = 20
    fmt.Println(x)   // 20
}

Pointer types

var p *int       // nil pointer
var s *string    // nil pointer

x := 42
p = &x           // points to x

Passing by value vs pointer

func byValue(x int) {
    x = 100 // Only changes local copy
}

func byPointer(x *int) {
    *x = 100 // Changes the original
}

func main() {
    a := 5
    byValue(a)
    fmt.Println(a) // 5

    byPointer(&a)
    fmt.Println(a) // 100
}

New and make

// new: allocates memory, returns pointer
p := new(int)
fmt.Println(*p) // 0

// make: initializes slices, maps, channels
s := make([]int, 5)
m := make(map[string]int)
ch := make(chan int)

Nil pointers

var p *int
fmt.Println(p == nil) // true

// Dereferencing nil causes panic
// fmt.Println(*p) // PANIC!

Best practices

  • Use pointers for large structs to avoid copying
  • Use pointers when you need to modify the original
  • Return errors instead of nil pointers
  • Use new for single allocations, make for slices/maps/channels

Mini Practice

Write Go code that:

  1. Swaps two integers using pointers
  2. Uses new to allocate a struct
  3. Demonstrates pass-by-value vs pass-by-pointer
  4. Shows nil pointer checking

Up Next

In the next lesson, you'll learn about Methods — functions on types.

Related Topics

Frequently Asked Questions about Pointers

What is Pointers in Go?

Pointers is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Pointers?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Pointers.

Why is Pointers important in Go?

Pointers is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.