2017-07-12 50 views
1

我來自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()函數返回一個stringint,取決於它是否從StringGeneratorIntGenerator

稱爲當我嘗試編譯這個時,出現以下錯誤:

不能使用s(鍵入* StringGenerator)類型Generatorer在陣列或 切片文字: * StringGenerator沒有實現Generatorer(錯誤類型getValue方法)

具有的getValue()字符串
想要的getValue( )

我該如何做到這一點?

+1

你想達到什麼目的?你將如何在Java中做同樣的事情?根據其實現情況,可以返回不同內容的接口有什麼用處?這聽起來不像我的界面的正確工作(無論是在Go還是在Java中)。 –

+0

@VincentvanderWeele我在stackreview上提交了我的代碼:https://codereview.stackexchange.com/questions/168955/generate-thousands-of-json-documents-in-go。這個問題解釋了項目的目標以及爲什麼我需要界面來解決我的問題! – felix

+0

啊,一切都是動態的,這就解釋了! Go的主要優勢在於靜態類型問題,所以我會說這個問題並不是語言的最佳匹配。當然這是可能的,就像在Java [反射](https://golang.org/pkg/reflect/)中最有可能的解決方案一樣。 –

回答

2

可以實現它:

type Generatorer interface { 
    getValue() interface{} 
} 

type StringGenerator struct { 
    length   int 
} 

type IntGenerator struct { 
    min   int 
    max   int 
} 

func (g StringGenerator) getValue() interface{} { 
    return "randomString" 
} 

func (g IntGenerator) getValue() interface{} { 
    return 1 
} 

空接口允許每個值。這允許通用代碼,但基本上阻止您使用Go的非常強大的類型系統。

在你的例子中,如果你使用getValue函數,你將得到一個類型爲interface{}的變量,如果你想使用它,你需要知道它是一個字符串還是int:你需要很多reflect使你的代碼變慢。

來自Python我習慣於編寫非常通用的代碼。在學習Go時,我不得不停止這樣思考。

這是什麼意思在你的具體情況我不能說,因爲我不知道什麼StringGeneratorIntGenerator被用於。

0

你無法達到你想要的樣子。但是,您可以聲明該功能爲:

type Generatorer interface { 
    getValue() interface{} 
} 

如果您希望它在不同的實現中返回不同的類型。以這種方式