← Back to Go Course | Chapter 8: Pointers | Lesson 1 of 6

Pointer Basics

A pointer is a note that says 'the real thing isn't here, it's over there' -- instead of holding the value itself, it holds directions to where the value actually lives.

What Is a Pointer?

A pointer variable stores the memory address of another value, rather than the value itself. In Go, a pointer to a type T is written *T, and you obtain one with the & (address-of) operator on an existing value.

Example: What Is a Pointer?

markup
package main

import "fmt"

func main() {
	x := 10
	p := &x
	fmt.Println("value of x:", x)
	fmt.Println("address stored in p:", p)
}

Dereferencing a Pointer

Dereferencing with *p retrieves the actual value stored at the address a pointer holds -- it's the operation that goes 'follow this address and give me what's there'.

Example: Dereferencing a Pointer

markup
package main

import "fmt"

func main() {
	x := 10
	p := &x
	fmt.Println("dereferenced value:", *p)
}

Pointers Enable Automatic Garbage Collection

Unlike C, Go manages memory for you -- you never manually free a pointer's memory. The garbage collector tracks when a value is no longer reachable through any pointer and reclaims it automatically.

Example: Pointers Enable Automatic Garbage Collection

markup
package main

import "fmt"

func newValue() *int {
	v := 42 // safely escapes to the heap; Go's GC manages its lifetime
	return &v
}

func main() {
	p := newValue()
	fmt.Println(*p)
}
Common Mistakes
  1. Confusing & (address-of) with * (dereference) -- & gets a pointer to a value, * gets the value a pointer points to.
  2. Assuming pointers require manual memory management like in C -- Go's garbage collector handles freeing memory automatically.
  3. Printing a pointer variable directly and being confused by the hexadecimal memory address instead of dereferencing it first to see the value.
Chapter Summary
  • A pointer holds the memory address of a value, rather than the value itself.
  • &x gets the address of x (a pointer); *p gets the value a pointer p points to.
  • Go pointers are garbage collected -- there's no manual malloc/free like in C.
  • Pointers are used to let a function modify a caller's variable, or to avoid copying large values.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.