Pointer Dereferencing in Go Explained
To understand pointer dereferencing, we'll delve into the Go code example you provided. In the original example, several instances of the Vertex struct are created, including *q which is a pointer to a Vertex. In your modified version, you assign the dereferenced value of *q to t. However, the key difference is that in your modification, you change q.X to 4, which updates the original instance pointed to by q.
The pointer *q points to the same underlying struct instance as q. So, by changing the value of q.X, you're altering the original struct, not creating a copy. Therefore, when you print t after modifying q.X, you'll notice that t does not reflect the change because t is storing a copy of the original struct, and not pointing to the same location as q.
To observe these changes through a pointer, you should directly assign q to t instead of dereferencing it. In the C/C example you mentioned, the behavior is similar. Dereferencing a pointer (e.g., *q) creates a copy of the value, while directly assigning the pointer (e.g., t = q) allows you to modify the original value through the pointer.
The above is the detailed content of How Does Pointer Dereferencing Affect Struct Copying in Go?. For more information, please follow other related articles on the PHP Chinese website!