What if your function could change your data instantly, without messy copying or confusion?
Why Pointer behavior in functions in Go? - Purpose & Use Cases
Imagine you want to change a value inside a function and see that change outside the function too, like updating a shared shopping list. But if you just pass the value, the function only changes its own copy, not the original list.
Manually copying values means every change stays local inside the function. You have to return the new value and remember to assign it back, which is slow and easy to forget. This leads to bugs where your program doesn't update data as expected.
Using pointers lets you give the function the address of the original data. The function can then directly change the original value, like handing over the actual shopping list instead of a copy. This makes updates clear, fast, and reliable.
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 functions to directly modify original data, making your programs more efficient and easier to manage.
Think of a function that updates a user's score in a game. Using pointers, the function can change the actual score stored in memory, so the updated score is immediately available everywhere.
Passing values copies data, so changes inside functions don't affect originals.
Pointers let functions access and modify original data directly.
This avoids extra copying and keeps data consistent across your program.