How does pointer dereferencing work in Go?

前端 未结 1 1211
谎友^
谎友^ 2020-12-30 21:28

I\'m going through the golang tutorials at http://tour.golang.org/, and was experimenting a bit with some things in example 29

For your reference, the original examp

1条回答
  •  隐瞒了意图╮
    2020-12-30 22:03

    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:

    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 
    
    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 }
    

    0 讨论(0)
提交回复
热议问题