我正在嘗試為類型參數設計模式實現指針方法示例的變體,以便抽象一些統一的存儲庫接口。我的印象是該Person結構將繼承Entityif it composes的方法集*Entity,但我收到如下編譯時錯誤。有人可以解釋為什么不滿足類型約束以及如何修復此代碼嗎?為糟糕的標題道歉;如果有人可以提出改進的摘要,那就太棒了(我對 Go 還很陌生)。謝謝 :)package main// domaintype PEntity[E any] interface { *E SetID(id string)}type Entity struct { ID string}func (e Entity) SetID(id string) { e.ID = id}type Repository[E Entity, PE PEntity[E]] interface { Get(id string) *E}// datatype Person struct { *Entity}type PersonRepository interface { Repository[Person, *Person] // -> Person does not implement Entity AddPet(name string) // ...}
1 回答

暮色呼如
TA貢獻1853條經驗 獲得超9個贊
約束E Entity
——語法糖E interface{ Entity }
——有效地意味著類型集ofE
恰好包含一個類型 term Entity
,它是一個結構。
當你有確切的約束時,你只能用那個類型來滿足它們,所以它與根本沒有類型參數和聲明常規函數參數沒有太大區別。舉個例子幫助你理解:
func Foo[T int](v T) {}
實際上與以下內容相同:
func Foo(v int) {}
E Entity
因此,您可以只使用 struct來滿足約束Entity
。
顯然Person
不是Entity
。字段嵌入只影響嵌入類型的方法集,與類型標識無關。
如果將約束更改為僅方法(基本)接口——或者Entity
直接更改(游樂場)——,那么它將只考慮方法集并成功編譯:
type Repository[E interface{ SetID(id string) }, PE PEntity[E]] interface { Get(id string) *E }
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報
0/150
提交
取消