dongling5411 2015-08-07 19:58
浏览 172
已采纳

Golang使用接口实现数据库功能

Sorry for a bit dummy questions, but I'm kinda stuck.

So, I'm implementing wrapper above database driver for my application, and I need to keep it as portable as possible. I came to decision that interfaces are perfect match for this task. So, I have my database struct with some variables and app-specific methods, and two interface functions:

query(request string) error
flush() int? string?? struct?? slice????, error

Now you probably got the main question. How do I do return data that type "flush()" doesn't know? Can I return it by interface, and if I can, how to work with that?

Second question is pretty basic, but still it isn't clear to me. So, I have this database struct with two methods designed to be implemented by package user to use db driver he want.
Ho do I write it and how future implementation will look (there is an example on tour of go, but it's about interface for different structs with similar methods)
Hope you'll help me find an understanding :)

  • 写回答

1条回答 默认 最新

  • douyueqing1530 2015-08-07 20:05
    关注

    Yes, flush can just have the signiture;

    flush() interface{}, error
    

    How do you implement? Something like this with reasonable method bodies should do it for you;

    type MyDbDriver struct {
         //fields
    }
    
    func (d *MyDbDriver) query(request string) error {
         return nil
    }
    
    func (d *MyDbDriver) flush() interface{}, error {
          return nil, nil
    }
    

    In Go all interface implementations are implicit, meaning, if your type has methods that match the interfaces signature, then you've implemented it. No need for something like public class MyType: IMyInterface, IThisIsntCSharp. Note that in the example above *MyDbDriver has implemented your interface but MyDbDriver has not.

    Edit: below a some pseudo calling code;

    e := driver.query("select * from thatTable where ThatProperty = 'ThatValue'")
    if e != nil {
        return nil, e
    }
    
    i, err := driver.flush()
    if err != nil {
         return nil, err
    }
    
    MyConcreteInstance := i.(MyConcreteType)
    // note that this will panic if the type of i is not MyConcreteType
    // that can be avoided with the familiar object, err calling syntax
    MyConcreteIntance, ok := i.(MyConcreteType)
    if !ok {
          // the type of i was not MyConcreteType :\
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件