将go结构体的项内联还是逐行显示。

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

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
}

引用自规范:结构体类型

结构体是一系列具有名称和类型的命名元素,称为字段。

定义结构体的三个要素,只要你改变的是行数,它们都是相同的:

  1. 顺序将保持不变(序列)
  2. 名称将保持不变
  3. 类型将保持不变
英文:

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(&quot;%T\n%T\n&quot;, 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:

  1. Order will be the same (sequence)
  2. Name will be the same
  3. Type will be the same

答案2

得分: 0

没有区别。只需选择对你来说更容易阅读的方式。

英文:

There is no difference. Just choose whatever is easier to read for you.

huangapple
  • 本文由 发表于 2017年3月17日 21:19:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/42858628.html
匿名

发表评论

匿名网友

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

确定