0
0
Goprogramming~3 mins

Why Common pointer use cases in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how pointers can save your program from wasting memory and speed!

The Scenario

Imagine you have a big box of photos and you want to share some with friends. You could try to make copies of each photo to give away, but that takes a lot of time and space.

The Problem

Copying big data over and over wastes memory and slows down your program. Also, if you want to change something in the original, you have to update every copy manually, which is easy to forget and causes mistakes.

The Solution

Pointers let you share the address of the original data instead of copying it. This way, everyone looks at the same photo, and if you change it once, everyone sees the update instantly.

Before vs After
Before
func updateValue(val int) {
    val = 10
}

func main() {
    x := 5
    updateValue(x)
    // x is still 5
}
After
func updateValue(val *int) {
    *val = 10
}

func main() {
    x := 5
    updateValue(&x)
    // x is now 10
}
What It Enables

It enables efficient memory use and easy updates by sharing data locations instead of copying data.

Real Life Example

When building a game, pointers let you update a player's health or position directly without copying the whole player data every time something changes.

Key Takeaways

Pointers avoid unnecessary copying of data.

They allow functions to modify original variables.

They help programs run faster and use less memory.