Pointers

Duration: 10 min  •  Difficulty: Hard

A Pointer is a variable that stores the memory address of another variable, instead of its value.

Why use Pointers?

1. Efficiency: If we send large data (e.g., a Struct with 100 fields) to a function, without pointers, that data will be copied (duplicated). With pointers, we only send the "address" (small and lightweight).

2. Modification: Allows a function to change the original value of a variable located outside that function.

Symbols

  • & (Ampersand): Gets the memory address of a variable ("Where do you live?").
  • * (Asterisk): Gets the value at that address ("Who lives at this address?").
  • MAIN.GO
    package main
    import "fmt"
    // This function receives a POINTER to an int (*int)
    func changeValue(ptr *int) {
    *ptr = 0 // Change the value at that memory address
    }
    func main() {
    i := 100
    fmt.Println("Initial:", i)
    // We send the memory ADDRESS of i (&i)
    changeValue(&i)
    // The value of i changes because we manipulated its original address
    fmt.Println("Final:", i)
    }