Interface method with multiple return types

a 夏天 提交于 2020-05-30 07:16:49

问题


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
}

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:

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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/45055953/interface-method-with-multiple-return-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!