亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang 結構沒有實現接口?

golang 結構沒有實現接口?

Go
qq_遁去的一_1 2022-11-23 10:26:12
我是 go 的初學者,所以請多多包涵。我有一個定義如下的接口: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接口,然后將其用于模擬和單元測試。然而,這會導致創建新 Repo 時出現問題: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})這對我來說很奇怪,因為據我所知,具有相同簽名的接口Run() error對于結構來說應該足夠了。Put我不確定我在這里做錯了什么。
查看完整描述

1 回答

?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

方法 Put 的類型錯誤(有 func(item interface{}) *github.com/guregu/dynamo.Put,想要 func(item interface{}) interface{Run() error})


你的函數返回一個*Put. 該接口需要一個interface{Run() error}. A*Put可能滿足這個接口,但它們仍然是不同的類型。 返回滿足該接口的類型的函數簽名不能與返回該接口的函數簽名互換。


因此,首先為您的界面命名。我們在兩個地方提到它,你應該避免匿名接口(和結構)定義,因為它們沒有內在的好處,會讓你的代碼更冗長,更少 DRY。


type Runner interface{

   Run() error

}

現在更新 DynamoTable 以使用該接口


type DynamoTable interface {

    Put(item interface{}) Runner

}

你說dynamo.Table的是你無法控制的。但是您可以創建一個等于的新類型dynamo.Table,然后覆蓋該put方法。


在重寫的方法中,我們轉換dynamoTable回dynamo.Table,調用原來的dynamo.Table.Put,然后返回結果。


type dynamoTable dynamo.Table


func (table *dynamoTable) Put(item interface{}) Runner {

  return (*dynamo.Table)(table).Put(item)

}

dynamo.Table仍然可以返回一個*Put因為*Putimplements Runner。返回值將為Runner,基礎類型將為*Put。然后接口將得到滿足,錯誤將被修復。


https://go.dev/play/p/y9DKgwWbXOO說明了這個重新輸入和覆蓋過程是如何工作的。


查看完整回答
反對 回復 2022-11-23
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號