Home >Backend Development >Golang >How Does Pointer Dereferencing Work in Go, and How Does It Compare to C/C ?
Understanding Pointer Dereferencing in Go
Pointer dereferencing, a fundamental operation in Go, involves accessing the value pointed to by a pointer variable. In the example mentioned in the question, pointers are used to manipulate a custom struct, Vertex.
Pointers and Structs
The original example showcased the creation of Vertex instances, including a reference to a Vertex instance using a pointer. In the modified example, the following occurs:
t := *q q.X = 4
The first line dereferences the pointer q and assigns its underlying value to t, effectively creating a copy of the Vertex pointed to. Subsequently, modifying q.X updates the original Vertex instance but does not affect t because t holds a separate copy of the struct.
Avoiding Surprises with Pointers
To ensure that changes made through a pointer are reflected in other references, pointers should be used consistently. In the revised example below, both t and q point to the same underlying Vertex:
t := q
With this change, q.X = 4 now updates the Vertex instance accessed by both t and q, resulting in the expected output:
{1 2} &{4 2} {1 0} {0 0} &{4 2} {4 2} true
A Parallel in C/C
Contrary to the "extremely strange behavior" perception, C/C exhibits similar behavior when pointers are involved. The following C code demonstrates this:
Vertex v = Vertex{1, 2}; Vertex* q = &v; Vertex t = *q; q->x = 4; std::cout << "*q: " << *q << "\n"; std::cout << " t: " << t << "\n";
The output is analogous to the modified Go example:
*q: { 4, 2 } t: { 1, 2 }
Therefore, the pointer dereferencing behavior observed in Go aligns with the behavior of pointers in other programming languages, such as C/C .
The above is the detailed content of How Does Pointer Dereferencing Work in Go, and How Does It Compare to C/C ?. For more information, please follow other related articles on the PHP Chinese website!