Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple tags on the same Go struct member

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.

like image 326
Alexander Bauer Avatar asked Dec 04 '12 01:12

Alexander Bauer


People also ask

Can you have multiple tag strings in struct field in Go?

This meta-data is declared using a string literal in the format key:"value" and are separated by space. That is, you can have multiple tags in the same field, serving different purposes and libraries.

How do you use struct tags in Go?

A Go struct can be compared to a lightweight class without the inheritance feature. A struct tag is additional meta data information inserted into struct fields. The meta data can be acquired through reflection. Struct tags usually provide instructions on how a struct field is encoded to or decoded from a format.

What are struct tags?

In the Go programs, you can add an optional string literal to a struct field. This is known as a struct tag. It is used to hold meta-information for a struct field. You can then export the information in the field to other packages to execute an operation or structure the data appropriately.

How do Go tags work?

Tags are a way to attach additional information to a struct field. A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag.


1 Answers

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:"-"`
}
like image 73
Brian Dorsey Avatar answered Sep 22 '22 16:09

Brian Dorsey