1 回答

TA貢獻1830條經驗 獲得超3個贊
如果我正確理解你,你是說你的實現是耦合到config結構而不是接口。如果是這種情況,只需將使用 的參數替換config為接口,在本例中為PAAPI。
在下面的代碼中,DoSomethingWithStruct您想要的可能不是函數定義,而是DoSomethingWithInterface函數定義。
type PAAPI interface {
Foo() // just a stub method
}
type Config struct {}
func (config *Config) Foo() {
// do something
}
func DoSomethingWithStruct(config Config) {
// do something
}
// you probably want a method that uses your config through the interface
func DoSomethingWithInterface(config PAAPI) {
// do something
}
更進一步,如果在外部包中,您想實現接口只需定義另一個符合接口的結構。像下面這樣:
type ExternalConfig struct{}
func (config *ExternalConfig) Foo() {
// do something
}
與 Java 不同的是,implementsGo 中沒有顯式關鍵字。它基于動態類型編程語言中的一個熟悉的原則,基本上是鴨子類型。它隱含地知道該接口是在編譯時由結構實現的。
基于前兩段代碼,現在您可以調用DoSomethingWithInterface(ExternalConfig{}). 請注意,我內聯了ExternalConfig此處的實例,但您可以使用實際憑據創建它并DoSomethingWithInterface以相同的方式將其傳遞給它。希望這可以幫助。另外,如果我沒有完全達到目標,請隨時發表評論以詢問清楚。
- 1 回答
- 0 關注
- 212 瀏覽
添加回答
舉報