为什么要使用&在结构上签名? [英] Why should I use the & sign on structs?
问题描述
在getour中,有一个部分:结构文字.
In the gotour, there is a section: struct literals.
package main
import "fmt"
type Vertex struct {
X, Y int
}
var (
v1 = Vertex{1, 2} // has type Vertex
v2 = Vertex{X: 1} // Y:0 is implicit
v3 = Vertex{} // X:0 and Y:0
p = &Vertex{1, 2} // has type *Vertex
)
func main() {
fmt.Println(v1, p, v2, v3)
}
带&"的结构与不带&"的结构有什么区别?我知道那些带有&符的引用指向相同的参考,但是为什么我要在普通的引用符上使用它们呢?
What's the difference between a struct with an ampersand and the one without? I know that the ones with ampersands point to the same reference, but why should I use them over the regular ones?
var p = &Vertex{} // why should I use this
var c = Vertex{} // over this
推荐答案
注释几乎说明了这一点:
The comments pretty much spell it out:
v1 = Vertex{1, 2} // has type Vertex
p = &Vertex{1, 2} // has type *Vertex
与许多其他语言一样,&
获取地址后跟的标识符.当您想要一个指针而不是一个值时,这很有用.
As in many other languages, &
takes the address of the identifier following it. This is useful when you want a pointer rather than a value.
如果您需要了解有关编程中指针的更多信息,则可以从此,甚至维基百科页面.
If you need to understand more about pointers in programming, you could start with this for go, or even the wikipedia page.
这篇关于为什么要使用&在结构上签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!