0
0
Goprogramming~3 mins

Why Address and dereference operators in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change data instantly everywhere without making copies?

The Scenario

Imagine you have a list of friends' phone numbers written on paper. To update one number, you have to find the exact paper, erase the old number, and write the new one. If you copy the list to share, changing a number in your copy won't update the original list.

The Problem

Manually copying and updating values is slow and error-prone. You might update a copy but forget to update the original, causing confusion. Also, passing large data around wastes memory and time.

The Solution

Address and dereference operators let you work directly with the location of data, not just copies. This means you can update the original data easily and efficiently, like having a direct phone line instead of a paper copy.

Before vs After
Before
var x int = 10
var y int = x
 y = 20 // x stays 10
After
var x int = 10
var p *int = &x
*p = 20 // x is now 20
What It Enables

It enables efficient data updates and sharing by working directly with memory addresses, avoiding unnecessary copies.

Real Life Example

When building a game, you can pass a pointer to a player's health so multiple parts of the game can update it instantly without copying the health value everywhere.

Key Takeaways

Manual copying causes slow and error-prone updates.

Address operators get the location of data.

Dereference operators let you change the original data directly.