英文:
go struct items inline or each by line
问题
在Go语言中,创建结构体时,分组/内联添加项目和逐行声明项目有什么区别?
例如:
type Item struct {
a, b, c uint32
d uint32
}
与逐行声明项目的方式相比,像这样:
type Item struct {
a uint32
b uint32
c uint32
d uint32
}
只是项目表示的方式不同。
哪种方式被认为是最佳实践?
英文:
In Go, when creating a struct what is the difference between grouping / adding items inline, for example:
<!-- language: lang-golang -->
type Item struct {
a, b, c uint32
d uint32
}
Versus declaring items one by line, something like:
<!-- language: lang-golang -->
type Item struct {
a uint32
b uint32
c uint32
d uint32
}
Is just a matter of how items are represented.
What would be considered as the best practice to follow?
答案1
得分: 1
没有区别,这两种类型是相同的。
为了验证,看看这个例子:
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
}
引用自规范:结构体类型:
结构体是一系列具有名称和类型的命名元素,称为字段。
定义结构体的三个要素,只要你改变的是行数,它们都是相同的:
- 顺序将保持不变(序列)
- 名称将保持不变
- 类型将保持不变
英文:
There is no difference, the 2 types are identical.
To verify, see this example:
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))
Output (try it on the Go Playground):
struct { a uint32; b uint32; c uint32; d uint32 }
struct { a uint32; b uint32; c uint32; d uint32 }
true
You may put multiple fields in the same line to group fields that logically belong together, for example:
type City struct {
Name string
lat, lon float64
}
type Point struct {
X, Y float64
Weight float64
Color color.Color
}
Quoting from Spec: Struct types:
> A struct is a sequence of named elements, called fields, each of which has a name and a type.
3 things that define the struct, all which will be the same if the only thing you change is the "number" of lines you put them:
- Order will be the same (sequence)
- Name will be the same
- Type will be the same
答案2
得分: 0
没有区别。只需选择对你来说更容易阅读的方式。
英文:
There is no difference. Just choose whatever is easier to read for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论