首页 > 解决方案 > 在 go 结构中使用空结构作为字段的目的是什么?

问题描述

例如:

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"`
}

这个例子来自 Algorand 的源代码

标签: go

解决方案


查看codec库实现(可能在这里使用它的一个分支),一个带有名称的私有字段_struct用于为结构的每个字段定义标签“设置”:

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
    ...
}

之所以struct{}使用 type 而不是bool因为它事实上的意思是“没有数据”,在这里看起来更合适。

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


推荐阅读