Hello All,
I just started with Go, and am loving it. Am trying to do something like this in Go,
type BaseModel struct {
ID int
}
type User struct {
BaseModel
Surname string
}
type Base interface {
Get(id int) error
}
// Also I dont want to have to write this for User struct
func (b *BaseModel) Get(id int) {
err := sqlx.Get(b, "SELECT * FROM user WHERE id=? LIMIT 0,1", id)
if err != nil {
log.Fatal(err)
}
}
func init() {
sqlx.Open("mysql","root:1234@tcp(127.0.0.1:3306)/test")
}
func main() {
ur := User{}
ur.Get(1)
log.Print(ur) // this should print the user struct, and not the BaseModel struct
}
I know my problem is here
func (b *BaseModel) Get(id int) {
I want User to inherit the Get method and also should be able to change the table name base on the name of the struct that is calling the Get method err := sqlx.Get(b, "SELECT FROM *user WHERE id=? LIMIT 0,1", id)
I don't want to do this xxx.Get(&ur, 1)
where xxx
can be an orm/sqlx/hood
评论:
nagai:
bogdanbursuc:Trying to write OOP in Go is going to leave you very sad and disappointed - there is no concept of inheritance here and if there is it's a very limited one. Try to figure out the Go way of doing things instead.
adzcqe:This is very wrong. Golang doesn't have OOP and you shouldn't use it like this.
What go offers is embedding and it's really not anything close to OOP, might look like it's OOP, but it's not.
What you have is
User
struct containing aBaseModel
field, and yourBaseModel.Get
is trying to access the user table which makes it really tied to your user anyway.When you do
sqlx.Get
you are setting theBaseModel
field and none of theUser
fields because theGet
method on theBaseModel
doesn't even have access to any of theUser
fields and doesn't even know that it's part of another struct. TheGet
method is called with theBaseModel
as receiver notUser
receiver.
Hek1t:The code is wrong, I know, That is why i comment on it. Its just to make the code work, since there is not table called
base_model
I know Go lang is not OOP, I just want to know if it is possible to do
ur.Get(1)
in pace ofxxx.Get(&ur, 1)
fudge21:Does this approach will work in other OOP languages?
Method Get () should know about inner structure of retrieving object anyway so you can't write it once (Except of using reflect, but i think it's huge overengineering)
watr:this might be getting at what you're trying to do but it's ugly...https://play.golang.org/p/llAqEKv5b4
womplord1:
Heresy
