假設我必須實現在兩個不同的包中聲明的兩個不同的接口(在兩個不同的獨立項目中)。我在包裹里 Apackage Atype interface Doer { Do() string}func FuncA(Doer doer) { // Do some logic here using doer.Do() result // The Doer interface that doer should implement, // is the A.Doer}并在包 Bpackage Btype interface Doer { Do() string}function FuncB(Doer doer) { // some logic using doer.Do() result // The Doer interface that doer should implement, // is the B.Doer}在我的main包裹里package mainimport ( "path/to/A" "path/to/B")type C int// this method implement both A.Doer and B.Doer but// the implementation of Do here is the one required by A !func (c C) Do() string { return "C now Imppement both A and B"}func main() { c := C(0) A.FuncA(c) B.FuncB(c) // the logic implemented by C.Do method will causes a bug here !}如何處理這種情況?
2 回答

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
正如常見問題中提到的
使用其他語言的經驗告訴我們,擁有多種名稱相同但簽名不同的方法有時很有用,但在實踐中也可能會令人困惑和脆弱。
僅按名稱匹配并要求類型一致是 Go 類型系統中的一個主要簡化決策。
在您的情況下,您會滿足兩個接口。
您可以通過執行以下操作來測試對象(接口類型)是否滿足另一種接口類型A.Doer
:
if _, ok := obj.(A.Doer); ok { }
OP補充說:
但是
Do
方法中實現的邏輯來滿足A
和B
.
然后你需要在你的對象周圍實現一個包裝器:
a
DoerA
,它將您的對象C
作為一個字段,并A.Do()
以滿足A.Do()
應該如何工作的方式實現a
DoerB
,它具有與C
字段相同的對象,并B.Do()
以滿足B.Do()
應該如何工作的方式實現
這樣,您將知道將哪個 Doer 傳遞給期望 anA.Doer
或 a的函數B.Doer
。
您不必Do()
在原始 object 上實現一個方法C
,這將無法處理A.Do()
and的不同邏輯B.Do()
。
- 2 回答
- 0 關注
- 270 瀏覽
添加回答
舉報
0/150
提交
取消