英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论