0
0
Goprogramming~3 mins

Passing values vs pointers in Go - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if you could change something once and have it update everywhere instantly?

The Scenario

Imagine you have a list of friends' names written on paper. You want to share this list with a friend, but instead of giving them the paper, you make a copy and hand it over. Now, if your friend changes something on their copy, your original list stays the same. But what if you wanted your friend to update your original list directly?

The Problem

Copying the entire list every time wastes paper and time. Also, if your friend changes their copy, your original list remains unchanged, causing confusion. Manually keeping track of which copy is the original and which is a duplicate is error-prone and slow.

The Solution

Using pointers is like giving your friend the exact address of your original list instead of a copy. They can directly update the original list, saving time and avoiding mistakes. This way, changes are shared instantly without making multiple copies.

Before vs After
Before
func updateName(name string) {
    name = "NewName"
}

func main() {
    original := "OldName"
    updateName(original)
    // original is still "OldName"
}
After
func updateName(name *string) {
    *name = "NewName"
}

func main() {
    original := "OldName"
    updateName(&original)
    // original is now "NewName"
}
What It Enables

It enables efficient and direct updates to data without unnecessary copying, making programs faster and easier to manage.

Real Life Example

When editing a shared document online, instead of sending copies back and forth, everyone works on the same file location, so changes appear instantly for all.

Key Takeaways

Passing by value creates copies, which can be slow and cause outdated data.

Passing by pointer shares the original data, allowing direct updates.

Using pointers helps write efficient and clear programs.