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