具有多种返回类型的接口方法 [英] Interface method with multiple return types
问题描述
我正在为接口苦苦挣扎.考虑一下:
I'm struggling with interfaces. Consider this:
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
I want the getValue()
function to return a string
or an int
, depending on if it's called from StringGenerator
or IntGenerator
当我尝试对此进行编译时,出现以下错误:
When I try to compile this, I get following error:
不能将s(* StringGenerator类型)用作数组中的类型Generator或 切片文字: * StringGenerator未实现Generatorer(getValue方法的类型错误)
cannot use s (type *StringGenerator) as type Generatorer in array or slice literal: *StringGenerator does not implement Generatorer (wrong type for getValue method)
具有getValue()字符串
想要getValue()
have getValue() string
want getValue()
我该如何实现?
推荐答案
您可以以这种方式实现:
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类型系统.
The empty interface allows every value. This allows for generic code but basically stops you from using the very powerful type system of Go.
在您的示例中,如果使用getValue
函数,您将获得类型为interface{}
的变量,如果要使用它,则需要知道它实际上是字符串还是整数:您将需要很多reflect
使您的代码变慢.
In your example if you use the getValue
function, you will get a variable of type interface{}
and if you want to work with it, you need to know if it actually is a string or an int: you will need a lot of reflect
making your code slow.
来自Python,我习惯于编写非常通用的代码.学习Go时,我不得不停止这种想法.
Coming from Python I was used to code very generic. When learning Go I had to stop thinking that way.
在您的特定情况下,这不能代表我的意思,因为我不知道StringGenerator
和IntGenerator
的用途.
What that means in your specific case I can't say because I don't know what StringGenerator
and IntGenerator
are being used for.
这篇关于具有多种返回类型的接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!