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 :\
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败