【发布时间】:2017-07-12 11:06:45
【问题描述】:
我正在为接口而苦苦挣扎。考虑一下:
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 调用的
当我尝试编译时,我收到以下错误:
不能在数组中使用 s (type *StringGenerator) 作为类型 Generatorer 或 切片文字: *StringGenerator 没有实现 Generatorer(getValue 方法的类型错误)
有 getValue() 字符串
想要getValue()
我怎样才能做到这一点?
【问题讨论】:
-
你想达到什么目的?你会如何在 Java 中做同样的事情?可以根据实现返回不同内容的接口有什么用?对我来说,这听起来不太适合接口(无论是在 Go 中还是在 Java 中)。
-
@VincentvanderWeele 我已经在 stackreview 上提交了我的代码:codereview.stackexchange.com/questions/168955/…。这个问题解释了项目的目标以及为什么我需要接口来解决我的问题!
-
啊,一切都是动态的,这就解释了! Go 的主要优势在于静态类型问题,所以我想说这个问题不是该语言的最佳匹配。当然这是可能的,就像在 Java 中一样,reflection 很可能是解决方案。