小编典典

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

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
}

我希望getValue()函数返回a string 或an int
,具体取决于是否从StringGenerator或调用IntGenerator

当我尝试对此进行编译时,出现以下错误:

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

有getValue()字符串
要getValue()

我该如何实现?


阅读 448

收藏
2020-07-02

共1个答案

小编典典

可以 通过以下方式实现它:

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{}并且如果要使用它,则需要知道它实际上是字符串还是整数:您将需要reflect使代码变慢。

来自Python,我习惯于编写非常通用的代码。学习Go时,我必须停止这种想法。

在您的特定情况下,我无法说什么,因为我不知道该做什么StringGenerator以及IntGenerator正在被使用。

2020-07-02