为什么Go语言要求在变量名之前添加&符号?

huangapple go评论83阅读模式
英文:

Why does go require you to add & before a variable name?

问题

为什么你必须写 &t 而不是只写 t.req?

英文:

Here is a snippet that I am looking at:

var t txn
t.c = c
err := c.read(&t.req)

Why do you have to write &t and not just t.req?

答案1

得分: 6

你不总是需要使用 ampersand(&)。在你的例子中,这取决于 c.read 的签名,它要求一个指针(在类型之前加上 *,比如 *MyStruct)。& 返回一个值的地址,给你一个指向它的指针,所以 &t.req 满足 read 的签名。

要进一步了解,请参阅指针的常见问题地址运算符的规范

英文:

You don't always have to use the ampersand. In your example it depends on the signature of c.read, which asks for a pointer (* before the type, such as *MyStruct). & returns the address of a value, giving you a pointer to it, so &t.req satisfies read's signature.

For further reading, see the FAQ on pointers and the spec on Address operators.

huangapple
  • 本文由 发表于 2013年3月20日 02:32:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/15507689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定