我在一個包中有一個耗費時間的方法的結構,並且通過它的工廠函數構造也很費時。因此,在依賴於這個其他結構的包中,我希望能夠在創建後使用假工廠函數和僞結構對其進行測試。由於結構是通過工廠函數構造的,所以我想假冒工廠函數並在測試期間將另一個工廠函數傳遞到我的結構中。返回與接口一起使用的結構的Go函數類型
昂貴的包的一個例子是:
package expensive
import "fmt"
type myStruct struct{}
func (m *myStruct) DoSomething() {
fmt.Println("In Do something")
}
func (m *myStruct) DoSomethingElse() {
fmt.Println("In do something else")
}
// CreateInstance is expensive to call
func CreateInstance() *myStruct {
return &myStruct{}
}
使用此然後我的主要包裝看起來是這樣的:
package main
import "play/expensive"
func main() {
thing := structToConstruct{expensive.CreateInstance}
thing.performAction()
}
type myInterface interface {
DoSomething()
}
type structToConstruct struct {
factoryFunction func() myInterface
}
func (s *structToConstruct) performAction() {
instance := s.factoryFunction()
instance.DoSomething()
}
然而,這個代碼與錯誤抱怨:
.\main.go:6: cannot use expensive.CreateInstance (type func() *expensive.myStruct) as type func() myInterface in field value
但是,* expensive.myStruct 確實實現myInterface接口,所以我不明白爲什麼Go會抱怨此設置的類型安全。
因爲我已經@jmaloney guideance之後才意識到,我可能只是包裝器我的函數像這樣在我的主要方法:
wrapper := func() myInterface {
return expensive.CreateInstance()
}
thing := structToConstruct{wrapper}
,這對當時的作品,但我還是不明白爲什麼我可以」當函數期望返回該接口的實例時,使用一個實現了接口的結構,特別是在此修復程序中不需要類型斷言/轉換時,因爲它只是調用底層工廠函數。
編輯:我已經遇到這個建議,將其添加到該語言。該提案被否決:
https://github.com/golang/go/issues/12754
增加了一個有用的希望解釋我的回答你的問題的更新。 – jmaloney