簡體   English   中英

Golang使用接口實現數據庫功能

[英]Golang implementing database funcs using interfaces

抱歉,我的問題有些虛構,但我有點被卡住了。

因此,我正在為我的應用程序在數據庫驅動程序之上實現包裝器,並且需要使其盡可能地可移植。 我決定將接口與該任務完美匹配。 因此,我的數據庫結構具有一些變量和特定於應用程序的方法以及兩個接口函數:

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

現在您可能已經有了主要問題。 如何返回不知道類型為“ flush()”的數據? 我可以通過接口返回它嗎,如果可以的話,如何使用它呢?

第二個問題很基本,但是對我來說仍然不清楚。 因此,我為這個數據庫結構提供了兩種方法,這些方法旨在由程序包用戶使用他想要的db驅動程序來實現。
我該如何寫它以及將來的實現方式(有一個例子,這是關於使用相似方法的不同結構的接口)
希望你能幫助我找到理解:)

是的,同花順只能帶有簽名。

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這樣的東西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 :\
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM