Home >Backend Development >Golang >How Do Go's Struct Setters Handle Pass-by-Value vs. Pass-by-Reference?
Understanding Struct Setters in Go
In Go, structs can be passed into functions by reference or by value. When passed by reference, the function can modify the original struct. However, passing a struct by value leads to the creation of a new copy of the struct within the function, and any modifications made to this copy will not alter the original struct.
In the provided code example:
type T struct { Val string }
The struct T contains a single string field named Val.
func (t T) SetVal(s string) { t.Val = s }
The SetVal method receives a struct by value and attempts to modify its Val field. However, this does not work as expected because the function is operating on a copy of the struct.
func (t *T) SetVal2(s string) { (*t).Val = s }
The SetVal2 method, on the other hand, receives a pointer to a struct and can therefore modify the original struct. This is because Go dynamically type-checks pointers, allowing the function to access the underlying struct and modify its fields directly.
In summary, it is essential to understand that structs passed by value create a new copy, preventing any modifications made within the function from affecting the original struct. To modify the original struct from within a function, it must be passed by reference, using a pointer.
The above is the detailed content of How Do Go's Struct Setters Handle Pass-by-Value vs. Pass-by-Reference?. For more information, please follow other related articles on the PHP Chinese website!