What if you could change something once and have it update everywhere instantly?
Passing values vs pointers in Go - When to Use Which
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?
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.
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.
func updateName(name string) {
name = "NewName"
}
func main() {
original := "OldName"
updateName(original)
// original is still "OldName"
}func updateName(name *string) {
*name = "NewName"
}
func main() {
original := "OldName"
updateName(&original)
// original is now "NewName"
}It enables efficient and direct updates to data without unnecessary copying, making programs faster and easier to manage.
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.
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.