我来自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/)中最有可能的解决方案一样。 –