【问题标题】:Multiple tags on the same Go struct member同一个 Go 结构成员上的多个标签
【发布时间】:2012-11-21 14:04:09
【问题描述】:

我觉得这应该是一个小问题,但我已经尝试了我能想到的所有模式,但我没有任何运气。我有一个结构需要encoding/jsongithub.com/zeebo/bencode 包都可以编码。它恰好包含一个通道,该通道不能被任何一个包编码。因此,它需要携带标签"-",以便跳过该字段。

type Index struct {
    Data data
    Queue chan string `json:"-"`
}

这在使用json 包编码时有效,但使用bencode 包编码时失败。

type Index struct {
    Data data
    Queue chan string `bencode:"-"`
}

当然,这个块有互补的问题。我尝试过像json:"-",bencode:"-"*:"-""-"- 这样的标签语法。有解决办法吗?

谢谢大家。

【问题讨论】:

    标签: json reflection tags go


    【解决方案1】:

    当用于编码提示时,空格似乎是结构标记之间的分隔符。

    例子:

    type TaggedStructExample struct {
        ...
        J int `datastore:",noindex" json:"j"`
    }
    

    发件人:https://developers.google.com/appengine/docs/go/datastore/reference#Properties

    在你的情况下,尝试:

    type Index struct {
        Data data
        Queue chan string `bencode:"-" json:"-"`
    }
    

    【讨论】:

    • 那是我没有尝试过的一件事!非常感谢。
    • 来自golang.org/pkg/reflect/#StructTag:按照惯例,标签字符串是可选用空格分隔的键:“值”对的串联。每个键都是一个非空字符串,由除空格 (U+0020 ' ')、引号 (U+0022 '"') 和冒号 (U+003A ':') 以外的非控制字符组成。每个值都被引用使用 U+0022 '"' 字符和 Go 字符串文字语法。
    • 换句话说,空格是可选的,但没有其他分隔符起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2014-01-12
    相关资源
    最近更新 更多