简体   繁体   中英

go struct items inline or each by line

In Go , when creating a struct what is the difference between grouping / adding items inline, for example:

type Item struct {
    a, b, c uint32
    d       uint32
}

Versus declaring items one by line, something like:

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?

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM