英文:
Go Model subclassing for Controller with structs
问题
嗨,我正在尝试为我正在构建的REST API构建一个基本框架。我希望有一个包含常规CRUD操作的BaseController,并且我想为每个Controller定义一个Model。我认为我的方法已经相当完善了,唯一仍然无法正常工作的是每个组件的初始化。我收到了以下错误信息:
struct初始化器中的值太少
以及:
无法将Model字面量(类型为Model)用作数组元素中的User类型
我的方法如下:
type Model struct {
Id *bson.ObjectId
}
type Controller struct {
model *Model
arrayOfModels *[]Model
}
然后,例如:
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}},
}}
}
我与Mgo(MongoDB适配器)一起使用此API,因此我使用bson.ObjectId。
我想知道我做错了什么,是否应该使用这种方法,以及有什么更好的方法。
非常感谢您的帮助。
Sjors
英文:
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
答案1
得分: 1
我想知道我做错了什么。
User
不是用于嵌入Model
的Model
。你不能在需要Model
的地方使用User
类型的值。
在Go语言中,多态是通过接口实现的,而不是通过嵌入实现的。
此外,你试图使用继承,但Go语言不支持继承,所以忘记继承吧。这也意味着忘记你所熟悉的MVC模式。
另外,你在使用指针。不要这样做,因为指针的使用是有代价的,如果指针逃逸了一个简单的块作用域,指向的值将被分配到堆上而不是栈上。在更复杂的情况下,理解指针也更加困难。
你需要进行范式转换,不要试图将你的“面向对象”专业知识应用到Go语言中。相反,阅读文档,阅读其他代码,并学会如何以Go的方式思考。
英文:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论