1 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
t := *q復(fù)制指向的結(jié)構(gòu)體q。
如果您想觀察qthrough 的變化t,請(qǐng)堅(jiān)持使用指針:
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)
}
這會(huì)產(chǎn)生您可能正在尋找的輸出。
{1 2} &{4 2} {1 0} {0 0} &{4 2} {4 2} true
我不確定你覺(jué)得什么特別奇怪。C 和 C++ 的行為方式相同。考慮以下:
#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";
}
此 C++ 代碼的輸出顯示了相同的行為:
*q: { 4, 2 }
t: { 1, 2 }
- 1 回答
- 0 關(guān)注
- 205 瀏覽
添加回答
舉報(bào)