Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 559
Eefret Avatar asked Aug 27 '15 20:08

Eefret


2 Answers

That won't work to begin with, since you're not exporting the fields names.

Otherwise, you can use struct tags to name the json fields as you need

type Card struct {
    CardID  string `json:"cardId"`
    Name    string `json:"name"`
    CardSet string `json:"cardSet"`
    Type    string `json:"type"`
}
like image 94
JimB Avatar answered Nov 04 '22 19:11

JimB


You have to use json annotations on your model. Also, the fields have to be exported (upper case) or the unmarshaller won't be able to make use of them.

type Card struct {
  CardId  string `json:"cardId"`
  Name    string `json:"name"`
  CardSet string `json:"cardSet"`
  TheType    string  `json:"type"`
}
like image 36
evanmcdonnal Avatar answered Nov 04 '22 18:11

evanmcdonnal