【问题标题】:What is the purpose of having an empty struct in a go struct as a field?在 go 结构中使用空结构作为字段的目的是什么?
【发布时间】:2020-10-12 08:29:31
【问题描述】:

例如:

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

【问题讨论】:

  • @ttrasn 我已经阅读了您提供的问题和答案,但我无法弄清楚这个特定示例中存在空结构的原因。我同意 VisioN 我想了解为什么会有 _struct struct{} 它的用例是什么。我查看了项目的源代码,但找不到示例用例。

标签: go


【解决方案1】:

查看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{} 类型而不是bool,是因为它事实上的意思是“没有数据”,在这里看起来更合适。

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

【讨论】:

    猜你喜欢
    • 2018-05-12
    • 1970-01-01
    • 2015-12-16
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    相关资源
    最近更新 更多