Hi I'm trying to build a base framework for an REST API I'm building. I like to have one BaseController with regular CRUD actions. And I'd like to define a Model for each Controller. I think I'm pretty far with my approach, the only thing that still doesn't seem to work is the initialization of each component. I'm receiving this errors:
too few values in struct initializer
And:
cannot use Model literal (type Model) as type User in array element
My approach:
type Model struct {
Id *bson.ObjectId
}
type Controller struct {
model *Model
arrayOfModels *[]Model
}
And then for example:
type User struct {
Model
someField string
}
type UserController struct {
Controller
}
func NewUserController() UserController {
return UserController{Controller{
model: &User{Model{Id: nil}},
arrayOfModels: &[]User{Model{Id: nil}},
}}
}
I'm using this API together with Mgo (MongoDB adapter), and therefore I use bson.ObjectId
I'd like to know what I'm doing wrong and if I should use this approach and what could be better.
Help is greatly appreciated.
Sjors
I'd like to know what I'm doing wrong
A User
is not a Model
for embedding a Model
. You can't use a value of type User
where a Model
is needed.
Polymorphism in Go is done through interfaces, not embedding.
Also, you're trying to do inheritance; Go does not support inheritance -- forget inheritance. That also means forget MVC as you know it.
Also, you're using pointers to everything. Don't; a pointer is costly because if it escapes a simple block scope the pointed-to value will be allocated on the heap instead of the stack. It's also harder to reason about pointers in more complicated situations.
You need a paradigm-shift, don't try to apply your "OO"-expertise to Go. Instead read the documentation, read other code and learn how to think in Go.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.