Go, Software Development

Unable To Update Struct Instance Fields in Golang

We cannot update Struct instance fields in Golang! That is partly true because Golang passes arguments to function by value even when it is a struct instance. Aside from function parameters, the effect is the same for “receiver” arguments.

Sample Codes To Update Struct Fields in Golang

We will use some sample codes to show that we cannot update Struct instance fields by default. For example, we have the following codes. We have a struct and a receiver function in the codes that try to update the petOwner field with a new owner.

When we run the codes, we get the following output. Notice the value of the struct field petOwner does not change from Gary to Sarah.

Use Pointers To Modify Struct Fields’ Values

We need pointers to modify struct fields in Golang. Using pointers involves using the ampersand (&) and asterisk symbols before the variable name. When using the ampersand symbol, we get the memory address of the value a variable holds. For example, please look into the following codes.

We get the following result when we run these codes: the string karl and its location in the computer memory. The same thing happens when we apply to structs and their fields.

The memory location of the string varies between runs and even computers. Therefore, we cannot rely on the value to be some constant. If a pointer returns the memory location of the value a variable holds, how do we change the value? We use a deference operator, the asterisk (*) symbol in Golang (and other C-based programming languages).

For our Golang struct example codes, we can use the ampersand and asterisk symbols to update the struct fields. So, how do we change the codes? First, we slightly modify the definition of the updatePetOwner function.

Then, we call the function on the pointer variable.

Therefore, we have the following complete Golang codes.

When we run these new codes, we get the following output.

Alternatively, we can skip using the ampersand (&) symbol and directly can the new function on the struct instance. However, this can be tricky and could lead to misleading codes. For example, the following codes will not change the petOwner value from Gary to Sarah.

This technique is Golang’s shortcut to pointers, and the change will happen on the copy of the struct instance in the mutablePet variable, not in the myPet variable.

Therefore, when we print out the value of the mutablePet variable, we get the following output.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like