在Go ,在创建结构时,内联分组/添加项目有什么区别,例如:
type Item struct {
a, b, c uint32
d uint32
}
与逐行声明项目相比,类似于:
type Item struct {
a uint32
b uint32
c uint32
d uint32
}
只是项目如何表示的问题。
什么是应遵循的最佳实践?
最佳答案
没有区别,两种类型是一样的。
要验证,请看这个例子:
a := struct {
a, b, c uint32
d uint32
}{}
b := struct {
a uint32
b uint32
c uint32
d uint32
}{}
fmt.Printf("%T\n%T\n", a, b)
fmt.Println(reflect.TypeOf(a) == reflect.TypeOf(b))
输出(在 Go Playground 上尝试):
struct { a uint32; b uint32; c uint32; d uint32 }
struct { a uint32; b uint32; c uint32; d uint32 }
true
您可以将多个字段放在同一行中以将逻辑上属于一起的字段分组,例如:
type City struct {
Name string
lat, lon float64
}
type Point struct {
X, Y float64
Weight float64
Color color.Color
}
A struct is a sequence of named elements, called fields, each of which has a name and a type.
定义结构的 3 件事,如果您唯一更改的是放置它们的行的“数量”,那么所有这些都将相同:
关于go struct items inline 或 each by line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858628/