erantis
erantis

Reputation: 51

Golang - Missing expression error on structs

type Old struct {
    UserID int `json:"user_ID"`
    Data   struct {
        Address string `json:"address"`
    } `json:"old_data"`
}

type New struct {
    UserID int `json:"userId"`
    Data   struct {
        Address string `json:"address"`
    } `json:"new_data"`
}

func (old Old) ToNew() New {
    return New{
        UserID: old.UserID,
        Data: { // from here it says missing expression
            Address: old.Data.Address,
        },
    }
}

What is "missing expression" error when using structs? I am transforming old object to a new one. I minified them just to get straight to the point but the transformation is much more complex. The UserID field for example works great. But when I use struct (which intended to be a JSON object in the end) the Goland IDE screams "missing expression" and the compiler says "missing type in composite literal" on this line. What I am doing wrong? Maybe should I use something else instead of struct? Please help.

Upvotes: 3

Views: 4403

Answers (2)

Mostafa Talebi
Mostafa Talebi

Reputation: 9173

You're defining Data as an inline struct. When assigning values to it, you must first put the inline declaration:

func (old Old) ToNew() New {
    return New{
        UserID: old.UserID,
        Data: struct {
        Address string `json:"address"`
    }{
            Address: old.Data.Address,
        },
    }
}

Hence it is generally better to define a separate type for Data, just like User.

Upvotes: 4

Julia
Julia

Reputation: 2085

Data is an anonymous struct, so you need to write it like this:

type New struct {
    UserID int `json:"userId"`
    Data   struct {
        Address string `json:"address"`
    } `json:"new_data"`
}

func (old Old) ToNew() New {
    return New{
        UserID: old.UserID,
        Data: struct {
            Address string `json:"address"`
        }{
            Address: old.Data.Address,
        },
    }
}

(playground link)

I think it'd be cleanest to create a named Address struct.

Upvotes: 7

Related Questions