Home > Backend Development > Golang > How Does Pointer Dereferencing Work in Go, and How Does It Compare to C/C ?

How Does Pointer Dereferencing Work in Go, and How Does It Compare to C/C ?

Linda Hamilton
Release: 2024-12-10 07:01:13
Original
141 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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";
Copy after login

The output is analogous to the modified Go example:

*q: { 4, 2 }
t: { 1, 2 }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template