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,
},
}
}
Run Code Online (Sandbox Code Playgroud)
使用结构时什么是“缺少表达式”错误?我正在将旧对象转变为新对象。我缩小了它们只是为了开门见山,但转换要复杂得多。例如,UserID字段效果很好。但是当我使用 struct (最终打算成为一个 JSON 对象)时,Goland IDE 会尖叫“缺少表达式”,并且编译器会在这一行显示“复合文字中缺少类型”。我做错了什么?也许我应该使用其他东西而不是结构?请帮忙。
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: struct {
Address string `json:"address"`
}{
Address: old.Data.Address,
},
}
}
Run Code Online (Sandbox Code Playgroud)
我认为创建一个命名结构是最干净的Address。