我來自java,目前正在嘗試學習去。我與interface
多種返回類型的接口方法
struggeling考慮這個問題:
type Generatorer interface {
getValue() // which type should I put here ?
}
type StringGenerator struct {
length int
}
type IntGenerator struct {
min int
max int
}
func (g StringGenerator) getValue() string {
return "randomString"
}
func (g IntGenerator) getValue() int {
return 1
}
我想getValue()
函數返回一個string
或int
,取決於它是否從StringGenerator
或IntGenerator
稱爲當我嘗試編譯這個時,出現以下錯誤:
不能使用s(鍵入* StringGenerator)類型Generatorer在陣列或 切片文字: * StringGenerator沒有實現Generatorer(錯誤類型getValue方法)
具有的getValue()字符串
想要的getValue( )
我該如何做到這一點?
你想達到什麼目的?你將如何在Java中做同樣的事情?根據其實現情況,可以返回不同內容的接口有什麼用處?這聽起來不像我的界面的正確工作(無論是在Go還是在Java中)。 –
@VincentvanderWeele我在stackreview上提交了我的代碼:https://codereview.stackexchange.com/questions/168955/generate-thousands-of-json-documents-in-go。這個問題解釋了項目的目標以及爲什麼我需要界面來解決我的問題! – felix
啊,一切都是動態的,這就解釋了! Go的主要優勢在於靜態類型問題,所以我會說這個問題並不是語言的最佳匹配。當然這是可能的,就像在Java [反射](https://golang.org/pkg/reflect/)中最有可能的解決方案一樣。 –