Development Blog
Collection of development articles I've put together...
Go: Value vs Reference types.
Say, you’re passing a variable to a function and you would like that function to update the given variable. This depends on the data type you’re passing in.
3
Likes
Stuart Todd
•
1 year ago
•
Best Practices
Value types (int, float, string, bool and structs) create a copy of the variable. If you adjust this copied variable within your function you won’t be updating the original. To update the original you’ll have to use a pointer.
Reference types (slices, maps, channels, pointers and functions) operate differently because they're not stored directly where they’re created. If you passed a variable to a function, a copy is made, however, like the original variable, this copy is already acting like a pointer to a value stored elsewhere.
E.g - a slice contains a reference to the actual lying list of records.