Home >Backend Development >Golang >Why Doesn't Dereferencing a Pointer in Go Update the Original Struct?
Pointer Dereferencing in Go
In Go, pointer dereferencing involves accessing the value stored in the memory address pointed to by a pointer variable.
Problem:
In an example provided by the Go tutorials, the expected behavior of pointer dereferencing does not occur. When a pointer variable is used to change a struct's value, the changes are not propagated to the dereferenced copy of the struct.
Explanation:
The t := *q operation creates a copy of the struct pointed to by q. Any changes made to q subsequently will not affect t. This behavior is expected because Go treats pointers as values, and assignments are copy operations.
To observe changes made through q in t, it is necessary to maintain a pointer to the struct rather than copying the value. This can be achieved by assigning q to t instead:
t := q
C/C Comparison:
The pointer dereferencing behavior in Go is similar to that in C/C . In both languages, pointers store the address of a value, and dereferencing them provides access to the actual value. However, in Go, assignments to pointers result in the copied value, whereas in C/C , they modify the referenced value directly.
The above is the detailed content of Why Doesn't Dereferencing a Pointer in Go Update the Original Struct?. For more information, please follow other related articles on the PHP Chinese website!