具有多种返回类型的接口方法

fel*_*lix 2 interface object go

我正在为接口而苦苦挣扎。考虑一下:

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
}
Run Code Online (Sandbox Code Playgroud)

我希望getValue()函数返回 astring或 an int,具体取决于它是从StringGeneratorIntGenerator

当我尝试编译它时,出现以下错误:

不能将 s(类型 *StringGenerator)用作数组或切片文字中的类型 Generatorer:*StringGenerator 未实现 Generatorer(getValue 方法的类型错误)

有 getValue() 字符串
想要 getValue()

我怎样才能做到这一点?

Teh*_*inX 5

可以通过这种方式实现它:

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
}
Run Code Online (Sandbox Code Playgroud)

空接口允许每个值。这允许通用代码,但基本上阻止您使用非常强大的 Go 类型系统。

在您的示例中,如果您使用该getValue函数,您将获得一个类型的变量,interface{}如果您想使用它,您需要知道它实际上是一个字符串还是一个 int:您将需要很多reflect使您的代码变慢。

来自 Python 我习惯于编写非常通用的代码。在学习围棋时,我不得不停止那样思考。

在你的具体情况下这意味着什么我不能说,因为我不知道是什么StringGenerator以及IntGenerator被用来做什么。