【发布时间】:2019-05-04 08:26:03
【问题描述】:
假设我有 3 个结构:
type A struct{
Foo map[string]string
}
type B struct{
Foo map[string]string
}
type C struct{
Foo map[string]string
}
然后我想创建一个可以接受任何这些结构的函数:
func handleFoo (){
}
有没有办法用 Golang 做到这一点?比如:
type ABC = A | B | C
func handleFoo(v ABC){
x: = v.Foo["barbie"] // this would be nice!
}
好的,让我们尝试一个界面:
type FML interface {
Bar() string
}
func handleFoo(v FML){
z := v.Bar() // this will compile
x: = v.Foo["barbie"] // this won't compile - can't access properties like Foo from v
}
在一种鼓励/强制组合的语言中,我无法理解为什么你不能访问像 Foo 这样的属性。
【问题讨论】:
-
技术上我不认为这是泛型本身,它与类型层次结构或接口有关
-
在任何其他情况下,当你告诉自己“我需要泛型”时,准备好像疯子一样复制粘贴(或代码生成,这实际上是同样糟糕的解决方案)
-
对于问题中显示的类型和
handleFoo,可以使用func handleFoo(v struct{ Foo map[string]string })See it in the Playground。这种方法有局限性。例如,handleFoo无权访问类型 A、B 或 C 中的任何方法。 -
Go 没有泛型。试图伪造它是一个愚蠢的想法。您的代码的目标是什么?让我们专注于您的问题,而不是您不受支持的解决方案。事实上,这是一个XY Problem。
-
接受不同的类型很容易。这就是接口的用途。
标签: go