Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

go struct items inline or each by line

Tags:

struct

go

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?

like image 841
nbari Avatar asked Oct 19 '25 02:10

nbari


1 Answers

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
like image 179
icza Avatar answered Oct 21 '25 14:10

icza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!