Search code examples
structgoreserved-words

Struct field with reserved name golang


Hi Im doing an API client and I want to use a struct to pull out the json, the problem is that one of the json fields should be named type, as far as I know it is a reserved keyword, how can I create a struct with a "type" field in it?

Example:

What I want to do:

type Card struct {
  cardId  string
  name    string
  cardSet string
  type    string
}

Solution

  • That won't work because you're not exporting the field names. To use different field names in the JSON output, you can use struct tags. For example, to name the fields CardID, Name, CardSet, and Type in the JSON output, you can define your struct like this:

    type Card struct {
        CardID  string `json:"cardId"`
        Name    string `json:"name"`
        CardSet string `json:"cardSet"`
        Type    string `json:"type"`
    }
    

    The json:"<name>" tags specify the field names to use in the JSON output.