2017-07-12 51 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{} 
} 

如果您希望它在不同的实现中返回不同的类型。以这种方式