草庐IT

go struct items inline 或 each by line

coder 2023-07-02 原文

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
}

引自Spec: Struct types:

A struct is a sequence of named elements, called fields, each of which has a name and a type.

定义结构的 3 件事,如果您唯一更改的是放置它们的行的“数量”,那么所有这些都将相同:

  1. 顺序相同(顺序)
  2. 姓名将相同
  3. 类型相同

关于go struct items inline 或 each by line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858628/

有关go struct items inline 或 each by line的更多相关文章

随机推荐