Help with OOP like feature in Go

blov · 2017-03-27 10:00:16 · 712 次点击    
这是一个分享于 2017-03-27 10:00:16 的资源,其中的信息可能已经有所发展或是发生改变。

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:

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.

bogdanbursuc:

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 a BaseModel field, and your BaseModel.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 the BaseModel field and none of the User fields because the Get method on the BaseModel doesn't even have access to any of the User fields and doesn't even know that it's part of another struct. The Get method is called with the BaseModel as receiver not User receiver.

adzcqe:

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 of xxx.Get(&ur, 1)

Hek1t:

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)

fudge21:

this might be getting at what you're trying to do but it's ugly...https://play.golang.org/p/llAqEKv5b4

watr:

You are looking for this.

womplord1:

Heresy


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

712 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传