Spyros K
Spyros K

Reputation: 2605

Initializing a variable in a struct while declaring a custom json name returns syntax error: unexpected literal

I want to declare a variable inside a struct, initialize it and at the same time declare a custom json name for it. However the compiler always returns a syntax error.

It is possible to initialize the value during struct declaration for instance

type Person struct {
        CategoryId     string "Generic"    
        Name           string     `json:"name"`
        Surname        string     `json:"surname"`
    }

It is possible to declare a custom json name.

type Person struct {
        CategoryId     string  `json:"category_id"`    
        Name           string     `json:"name"`
        Surname        string     `json:"surname"`
    }

However the following code returns an error

type Person struct {
    CategoryId     string "Generic"  `json:"category_id"`    
    Name           string     `json:"name"`
    Surname        string     `json:"surname"`
}

The error returned is the following

syntax error: unexpected literal json:"category_id", expecting semicolon or newline or }

What is the correct syntax? I tried several combinations like the following:

type Person struct {
    CategoryId     string "Generic"  `json:"category_id"`;  
    Name           string     `json:"name"`
    Surname        string     `json:"surname"`
}

type Person struct {
    CategoryId     string "Generic";  `json:"category_id"`
    Name           string     `json:"name"`
    Surname        string     `json:"surname"`
}

But none of the above is the correct syntax. I would also appreciate a link to where I can read more about this syntax.

Upvotes: 0

Views: 307

Answers (1)

icza
icza

Reputation: 418585

This field declaration:

CategoryId     string "Generic" 

Is not initialization (you can't specify default values for fields in Go in the type declaration). The string literal "Generic" at the end is the field's tag value. It's the same as this:

CategoryId     string `Generic` 

It doesn't matter if you use a raw or interpreted string literal, you may only provide a single literal there and it will be the field's tag.

If you want to provide multiple tag values for a single field, by convention you have to separate them with a space, in a single literal, e.g.:

CategoryId     string `Generic json:"category_id"`

The syntax is detailed in Spec: Struct types:

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. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

For an overview, more details and convention, I highly recommend to read this related question: What are the use(s) for tags in Go?

Upvotes: 2

Related Questions