Golang uses memory management for our variables so updating values in our structs as we defined in the previous article, doesn’t necessarily work as we expected.
Let’s say we have the below, this piece of data will be stored in a particular memory address, let’s say, address 001.
When we pass this object to a function in a receiver, we pass it (in the below example) as d. So, the instance of the detailed_emp struct is passed in as d.
We then call this function using the below, passing the name we want to update in the parenthesis.
This won’t work. Why? Because, as you remember, our object emp_with_contact_info is in memory address 001 but object ‘d’ which was passed into the function, is in memory address 002. So you aren’t updating the original version of the item.
This is where pointers come in. In the below, we take our emp_with_contact_info variable and we prefix it with an ampersand. This ampersand tells Golang to store the memory address NOT the actual variable content.
We then use the user_pointer memory address when calling the update_name() function.
When we pass that into the receiver for the function, we prefix the data type (detailed_emp) with a *. This * lets Golang know that you’re using a pointer, pointing to a type.
Next, we add an * infront of the statement where we change the firstName value. The * means we are referring to the memory address, not the value. The star gets it to return the value and update it.
So now, it will update the correct instance of the detailed_emp struct item, as it’s hitting the memory address directly.
When do we use pointers?
Some data types in Go require us to use pointers and others do not. Arrays for example, do require us to use pointers, while slices don’t. This is because a slice has a pointer to the underlying array, so when you reference an item in a slice, you’re kind of already using a pointer.
Require pointers (value data type):
Don’t require pointers (reference data type):