Skip to content

Module 4: Pointers (The Home Address)

📚 Module 4: Pointers

Course ID: GO-108
Subject: The Home Address

Pointers are often the scariest part of programming for beginners. But in Go, they are designed to be safe and simple. A pointer is just a Home Address.


🏗️ Step 1: Pass by Value (The “Copy”)

In Go, when you give a variable to a function, Go makes a Copy of it.

🧩 The Analogy: The House Photo

  • You have a house (The Variable).
  • You take a Photo of it and give it to a Painter (The Function).
  • The Painter paints the house Red in the photo.
  • When you look at your real house, it is still White. The painter only changed the copy!

🏗️ Step 2: Pass by Reference (The “Address”)

What if you want the Painter to change your Real House? You don’t give them a photo; you give them your Home Address.

🧩 The Analogy: The GPS Coordinates

  • You give the Painter a piece of paper with your address (The Pointer).
  • The Painter follows the address to your real house.
  • They paint the real walls Red.
  • Now, your real house has changed!

🏗️ Step 3: In Code

  • & (Address of): “Give me the address of this variable.”
  • * (Pointer to): “Follow the address to the real data.”
func paintRed(realHouseAddress *string) {
    *realHouseAddress = "Red" // Follow address and change real data
}

func main() {
    myHouse := "White"
    
    // Pass the ADDRESS using &
    paintRed(&myHouse)
    
    fmt.Println(myHouse) // Output: Red!
}

🥅 Module 4 Review

  1. Pointer: A variable that stores a memory address.
  2. & (Ampersand): Getting the address.
  3. * (Star): Following the address (Dereferencing).

:::tip Senior Tip In Go, we mostly use pointers for Structs to avoid copying large amounts of data, or when we need a function to modify the original data. Don’t use them for small things like int or bool unless necessary! :::