Home >Backend Development >Golang >Why can't we assign a value when we return a struct instead of a pointer to a struct?
In C language, when we return a structure instead of a pointer to the structure, the reason why we cannot directly assign the value is that the entire structure will be copied when returning the structure content instead of returning a pointer to the structure. Since a structure may contain a large amount of data, copying the entire structure may be expensive. Therefore, in order to improve efficiency, the C language stipulates that when a structure is returned, we can only use it by assigning it to a variable of structure type. This can avoid unnecessary copy operations and improve code execution efficiency.
Suppose we have the following structure
type profile struct { id int name string } func test(p profile) profile { return p } func main() { var profile profile test(profile).id = 20 // cannot assign to test(profile).id (value of type int) }
But if we change the profile
of the test function return type to *profile
, the main function will work.
func test(p Profile) *Profile { return &p } func main() { var profile Profile test(profile).id = 20 // Works }
Why is this?
Assigning fields to Profile
in this way has no noticeable effect. You are assigning a temporary struct value (of a field) and then immediately discarding it. Note that test's return value is a copy of the profile in main; it is copied into the test's parameters, and then copied again when returning from the test.
When returning a pointer, at least in principle, the structure pointed to will still be accessible after the assignment (although not in this particular case, since the pointer points to a copy of the argument being tested).
The above is the detailed content of Why can't we assign a value when we return a struct instead of a pointer to a struct?. For more information, please follow other related articles on the PHP Chinese website!