Lab 06: Pointers & Memory

Objective

Understand Go pointers: address-of operator, dereferencing, nil pointers, pointer to structs, and when to use pointers vs values.

Time

25 minutes

Prerequisites

  • Lab 04 (Structs & Methods)

Tools

  • Docker image: zchencow/innozverse-go:latest


Lab Instructions

Step 1: Pointer Basics

docker run --rm zchencow/innozverse-go:latest go run - << 'EOF'
package main

import "fmt"

func main() {
    x := 42
    p := &x         // p is a pointer to x (*int)

    fmt.Printf("x = %d\n", x)
    fmt.Printf("&x = %p (address of x)\n", &x)
    fmt.Printf("p = %p (value of p = address)\n", p)
    fmt.Printf("*p = %d (dereference p = value at address)\n", *p)

    *p = 99         // modify x via pointer
    fmt.Printf("After *p=99, x = %d\n", x)

    // new() — allocates zeroed memory, returns pointer
    q := new(int)
    fmt.Printf("new(int): %p → %d\n", q, *q)
    *q = 100
    fmt.Printf("After *q=100: %d\n", *q)

    // Nil pointer — zero value of any pointer type
    var ptr *int
    fmt.Printf("nil pointer: %v, isNil: %v\n", ptr, ptr == nil)
    // *ptr would panic! Always check for nil

    // Pointer to pointer
    pp := &p
    fmt.Printf("**pp = %d\n", **pp)
}
EOF

💡 &x gives the address, *p dereferences it. In Go, you never do pointer arithmetic (no ptr + 1 like C). The garbage collector tracks all pointers and moves/frees memory automatically. Dereferencing a nil pointer causes a panic — always check ptr != nil before dereferencing.

📸 Verified Output:


Step 2: Pointers to Structs

💡 Go automatically dereferences struct pointersp.Field and (*p).Field are identical. This is why &Config{} is so natural. When you use a pointer receiver method func (c *Config) Set(...), calling myConfig.Set(...) works even if myConfig is not a pointer — Go takes its address automatically.

📸 Verified Output:


Steps 3–8: Functional pointers, escape analysis, Tree, Optional, Capstone

📸 Verified Output:


Summary

Operation
Syntax
Effect

Address-of

p := &x

p holds address of x

Dereference

*p

Value at address

Modify via ptr

*p = val

Changes original

nil check

if p != nil

Must do before deref

new

p := new(T)

Allocates, returns *T

Struct pointer

p.Field same as (*p).Field

Auto-deref

Further Reading

Last updated