英文:
Struct Literals in Golang
问题
在Go语言中,结构体字面量的情况如下:
type Vertex struct {
X, Y int
}
var (
p = Vertex{1, 2} // 类型为Vertex
q = &Vertex{1, 2} // 类型为*Vertex
r = Vertex{X: 1, Y: 2}
)
变量p、q和r的值分别为{1 2}
、&{1 2}
和{1 2}
。
上述三个变量的初始化方法有何区别?变量p、q和r有何不同之处?
英文:
In case of Struct Literals in Go,
type Vertex struct {
X, Y int
}
var (
p = Vertex{1, 2} // has type Vertex
q = &Vertex{1, 2} // has type *Vertex
r = Vertex{X: 1, Y: 2}
)
The values for p, q and r are {1 2} &{1 2} {1 2}
What is the difference between the initialisation methods of the above three variables ? How are the variables p, q and r different ?
答案1
得分: 6
q
是指向在堆上分配的结构体的指针。其他的都是相同的,分配在栈上。无论你是否列出字段名,这纯粹是为了可读性,我建议尽可能这样做。
英文:
q
is a pointer to a struct allocated on the heap. The others are identical, and allocated on the stack. Whether you list the field names is purely for readability, and I suggest doing so whenever possible.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论