Discover how pointers can save your program from wasting memory and speed!
Why Common pointer use cases in Go? - Purpose & Use Cases
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.
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.
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.
func updateValue(val int) {
val = 10
}
func main() {
x := 5
updateValue(x)
// x is still 5
}func updateValue(val *int) {
*val = 10
}
func main() {
x := 5
updateValue(&x)
// x is now 10
}It enables efficient memory use and easy updates by sharing data locations instead of copying data.
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.
Pointers avoid unnecessary copying of data.
They allow functions to modify original variables.
They help programs run faster and use less memory.