【问题标题】:Golang implementing database funcs using interfacesGolang 使用接口实现数据库函数
【发布时间】:2015-08-07 19:58:58
【问题描述】:

抱歉,我问了一些愚蠢的问题,但我有点卡住了。

所以,我正在为我的应用程序在数据库驱动程序之上实现包装器,并且我需要尽可能地保持它的可移植性。 我决定接口非常适合这项任务。所以,我的数据库结构包含一些变量和特定于应用程序的方法,以及两个接口函数:

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

现在您可能得到了主要问题。如何返回“flush()”类型不知道的数据?我可以通过接口返回它吗?如果可以,如何使用它?

第二个问题非常基本,但我仍然不清楚。 所以,我有这个数据库结构,它有两种方法,旨在由包用户实现,以使用他想要的 db 驱动程序。
我如何写它以及未来的实现将如何(在 go 之旅中有一个示例,但它是关于具有相似方法的不同结构的接口)
希望你能帮助我找到理解:)

【问题讨论】:

    标签: database go interface


    【解决方案1】:

    是的,flush 可以只有签名;

    flush() interface{}, error
    

    你们是如何实施的?像这样具有合理方法主体的东西应该为您做;

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

    在 Go 中,所有接口实现都是隐式的,这意味着,如果您的类型具有与接口签名匹配的方法,那么您已经实现了它。不需要像public class MyType: IMyInterface, IThisIsntCSharp 这样的东西。请注意,在上面的示例中,*MyDbDriver 实现了您的接口,但 MyDbDriver 没有实现。

    编辑:下面是一些伪调用代码;

    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 :\
    }
    

    【讨论】:

    • 谢谢!但仍不清楚如何在调用者函数中处理此返回。当然,我知道我想通过 SQL 请求获得什么类型,但肯定有必要检查返回的类型。如何进行这种类型的错误检查?
    • @mersinvald 在调用代码中,您通常会使用“类型断言”或“类型开关”来拆箱数据。我将使用一个示例进行编辑(对于开发人员来说,它的工作方式很像演员阵容,尽管在概念上/内部它有点不同)。这个概念在语言规范golang.org/ref/spec#Type_assertions 中有介绍
    猜你喜欢
    • 2021-07-21
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多