同一个Go结构体成员上的多个标签

huangapple go评论83阅读模式
英文:

Multiple tags on the same Go struct member

问题

我觉得这应该是一个小问题,但是我尝试了我能想到的每种模式,但都没有成功。我有一个需要被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:"-"*:"-""-"-这样的标签语法。有解决方案吗?

谢谢大家。

英文:

I feel like this should be a minor problem, but I've tried every pattern that I can think of, and I haven't had any luck. I have a structure that needs to be encodable by both the encoding/json and github.com/zeebo/bencode packages. It happens to include a channel, which cannot be encoded by either package. Thus, it needs to carry the tag "-", so that that field is skipped.

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

This is valid when encoded by the json package, but fails with the bencode package.

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

This block, of course, has the complimentary problem. I have tried tag syntaxes like json:"-",bencode:"-", *:"-", "-", -. Is there a solution?

Thank you all.

答案1

得分: 25

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

示例:

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:"-"`
}
英文:

Spaces appear to be the delimiter between struct tags when used for encoding hints.

Example:

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

From: https://developers.google.com/appengine/docs/go/datastore/reference#Properties

In your case, try:

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

huangapple
  • 本文由 发表于 2012年12月4日 09:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/13694557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定