我是一個初學者,所以請耐心等待。我有一個定義如下的介面:
type DynamoTable interface {
Put(item interface{}) interface{ Run() error }
}
我也有一個Repo這樣的結構:
type TenantConfigRepo struct {
table DynamoTable
}
我有一個結構dynamo.Table,它的Put函式定義如下:
func (table dynamo.Table) Put(item interface{}) *Put
并且該Put結構具有Run如下功能:
func (p *Put) Run() error
我想要做的是有一個通用DynamoTable介面,然后將用于模擬和單元測驗。但是,這會導致創建新存盤庫出現問題:
func newDynamoDBConfigRepo() *TenantConfigRepo {
sess := session.Must(session.NewSession())
db := dynamo.New(sess)
table := db.Table(tableName) //=> this returns a type dynamo.Table
return &TenantConfigRepo{
table: table,
}
}
然而,這會引發這樣的錯誤
cannot use table (variable of type dynamo.Table) as DynamoTable value in struct literal: wrong type for method Put (have func(item interface{}) *github.com/guregu/dynamo.Put, want func(item interface{}) interface{Run() error})
這對我來說很奇怪,因為從我所看到的界面來看,具有 a 的介面Run() error對于結構來說應該足夠了,Put因為它具有相同的簽名。我不確定我在這里做錯了什么。
謝謝!。
uj5u.com熱心網友回復:
方法 Put 的型別錯誤(具有 func(item interface{}) *github.com/guregu/dynamo.Put,需要 func(item interface{}) interface{Run() error})
您的函式回傳一個*Put. 該介面需要一個interface{Run() error}. A*Put可能滿足這個介面,但它們仍然是不同的型別。 回傳滿足該介面的型別的函式簽名不能與回傳該介面的函式簽名互換。
因此,首先為您的界面命名。我們在 2 個地方參考它,你應該避免匿名介面(和結構)定義,因為它們沒有內在的好處,并使你的代碼更冗長,更少 DRY。
type Runner interface{
Run() error
}
現在更新 DynamoTable 以使用該界面
type DynamoTable interface {
Put(item interface{}) Runner
}
你說dynamo.Table的不在你的控制范圍內。但是您可以創建一個新型別 equal dynamo.Table,然后覆寫該put方法。
在重寫的方法中,我們將dynamoTableback 轉換為dynamo.Table,呼叫原來的dynamo.Table.Put,然后回傳結果。
type dynamoTable dynamo.Table
func (table *dynamoTable) Put(item interface{}) Runner {
return (*dynamo.Table)(table).Put(item)
}
dynamo.Table仍然可以回傳 a*Put因為*Putimplements Runner。回傳值將是Runner,基礎型別將是*Put. 然后界面將被滿足,并且該錯誤將被修復。
https://go.dev/play/p/y9DKgwWbXOO說明了這種重新輸入和覆寫程序是如何作業的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/443002.html
上一篇:如何在Go的介面中使用函式型別
