我正在嘗試為我正在構建的 REST API 構建一個基本框架。我喜歡有一個帶有常規 CRUD 操作的 BaseController。我想為每個控制器定義一個模型。我想我的方法已經很遠了,唯一似乎仍然不起作用的是每個組件的初始化。我收到此錯誤:too few values in struct initializer和:cannot use Model literal (type Model) as type User in array element我的做法: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}}, }}}我將此 API 與 Mgo(MongoDB 適配器)一起使用,因此我使用 bson.ObjectId我想知道我做錯了什么,我是否應該使用這種方法以及什么可以更好。
1 回答

陪伴而非守候
TA貢獻1757條經驗 獲得超8個贊
我想知道我做錯了什么
AUser
不是Model
用于嵌入 a Model
。您不能User
在Model
需要a 的地方使用類型的值。
Go 中的多態是通過接口完成的,而不是嵌入。
此外,您正在嘗試進行繼承;Go 不支持繼承——忘記繼承吧。這也意味著忘記你所知道的 MVC。
此外,您正在使用指向所有內容的指針。別; 指針代價高昂,因為如果它轉義簡單的塊作用域,指向的值將分配在堆上而不是堆棧上。在更復雜的情況下也更難推理指針。
您需要進行范式轉換,不要嘗試將您的“面向對象”專業知識應用于 Go。而是閱讀文檔,閱讀其他代碼并學習如何在 Go 中思考。
- 1 回答
- 0 關注
- 207 瀏覽
添加回答
舉報
0/150
提交
取消