我正在创建一个API,我有两个不同的结构用于JSON响应;一个用于单个记录,一个用于记录收集:
type Model struct {
Id uint
}
type Collection struct {
Records []Model
}
Model
只是数据库数据的结构表示(例如,用户),而Collection
是模型的集合。
问题在于会有单独的结构嵌入Model
类型,如下所示:
type User struct {
*Model
Name string
}
由于User
不符合Model
类型,我无法将其附加到Collection
结构中:
user := User{&Model{1}, "Jon"}
uc := &Collection{[]User{user}}
如何使Records结构接受实现Model
的结构类型?
答案 0 :(得分:4)
模型结构不是用户结构的类型 即使嵌入了用户,用户也无法表现出模型。
这种情况下,您可以使用如下界面 http://play.golang.org/p/Hh0zIT9yFC
package main import "fmt" type Model interface { GetID() uint } type BaseModel struct { Id uint } func (m BaseModel) GetID() uint { return m.Id } type Collection struct { Records []Model } type User struct { *BaseModel Name string } func (u User) GetName() string { return u.Name } func main() { user := User{&BaseModel{1}, "Jon"} uc := &Collection{[]Model{user}} u := uc.Records[0].(User) fmt.Println(u.GetID()) fmt.Println(u.GetName()) }