go

What is the purpose of having an empty struct in a go struct as a field?


For example:

rawVote struct {
    _struct  struct{}       `codec:",omitempty,omitemptyarray"`
    Sender   basics.Address `codec:"snd"`
    Round    basics.Round   `codec:"rnd"`
    Period   period         `codec:"per"`
    Step     step           `codec:"step"`
    Proposal proposalValue  `codec:"prop"`
}

this example from Algorand"s source code


Solution

  • Looking at codec library implementation (probably a fork of it is being used here), a private field with name _struct is used to define tag "settings" for every field of the structure:

    type MyStruct struct {
        _struct bool    `codec:",omitempty"`   //set omitempty for every field
        Field1 string   `codec:"-"`            //skip this field
        Field2 int      `codec:"myName"`       //Use key "myName" in encode stream
        Field3 int32    `codec:",omitempty"`   //use key "Field3". Omit if empty.
        Field4 bool     `codec:"f4,omitempty"` //use key "f4". Omit if empty.
        io.Reader                              //use key "Reader".
        MyStruct        `codec:"my1"`          //use key "my1".
        MyStruct                               //inline it
        ...
    }
    

    The reason why struct{} type is used instead of bool because it de-facto means "no data" and looks more appropriate here.

    SOURCE: https://github.com/algorand/go-codec/blob/master/codec/encode.go#L1418