How does pointer dereferencing work in Go?

t := *q makes a copy of the struct pointed to by q.

If you want to observe changes to q through t, then stick with a pointer:

var (
    p = Vertex{1, 2}  // has type Vertex
    q = &Vertex{1, 2} // has type *Vertex
    r = Vertex{X: 1}  // Y:0 is implicit
    s = Vertex{}      // X:0 and Y:0
)


func main() {
    t := q
    q.X = 4
    u := *q
    fmt.Println(p, q, r, s, t, u, *t == u)
}

This produces the output you were probably looking for.

{1 2} &{4 2} {1 0} {0 0} &{4 2} {4 2} true

I’m not sure what seems extremely strange to you. C and C++ behave the same way. Consider the following:

#include <iostream>

struct Vertex
{
    int x;
    int y;
};

std::ostream& operator<<(std::ostream& out, const Vertex& v)
{
    out << "{ " << v.x << ", " << v.y << " }"; 
    return out;
}

int main()
{
    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 of this C++ code shows the same behavior:

*q: { 4, 2 }  
t: { 1, 2 }

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)