具有多种返回类型的接口方法
I come from java and currently try to learn go. I'm struggeling with interface
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
}
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 folowing error :
cannot use s (type *StringGenerator) as type Generatorer in array or slice literal: *StringGenerator does not implement Generatorer (wrong type for getValue method)
have getValue() string
want getValue()
How can I achieve this ?
我来自Java,目前正在尝试学习。 我在与 挣扎考虑: p>
我想要 当我尝试对此进行编译时,出现以下错误: p>
不能在数组或
切片文字中使用s(类型* StringGenerator)作为类型Generatorer:
* StringGenerator不实现Generatorer(getValue方法的类型错误) p>
具有getValue()字符串 如何实现? p>
div> interface code> p>
type Generatorer接口{
getValue() //我应该在这里输入哪种类型?
}
type StringGenerator结构{
length int
}
type IntGenerator结构{
min int
max int
}
func(g StringGenerator)getValue()字符串{
返回“ randomString”
}
func(g IntGenerator)getValue()int {
返回1
}
code> pre>
getValue() code>函数返回
string code> strong>或
int code> strong>,具体取决于是否从
StringGenerator code>或
IntGenerator code> p>
要getValue() p>
blockquote>
You could achieve it in this way:
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
}
The empty interface allows every value. This allows for generic code but basically stops you from using the very powerful type system of Go.
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.
Coming from Python I was used to code very generic. When learning Go I had to stop thinking that way.
What that means in your specific case I can't say because I don't know what StringGenerator
and IntGenerator
are being used for.
You can't achieve this the way you want to. You can, however, declare the function as
type Generatorer interface {
getValue() interface{}
}
if you want it to return different types in different implementations.