Golang中的结构体字面量

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

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.

huangapple
  • 本文由 发表于 2014年6月9日 19:18:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/24119207.html
匿名

发表评论

匿名网友

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

确定