首页 > 解决方案 > Golang 泛型 - 简单用例

问题描述

假设我有 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 之类的属性。

标签: go

解决方案


您可以通过这种方式使用接口,添加一个方法GetFoo来获取每个结构的 foo 。

type A struct{
    Foo map[string]string
}

func(a *A) GetFoo() map[string]string {
    return a.Foo
}

type B struct{
    Foo map[string]string
}

func(b *B) GetFoo() map[string]string {
    return b.Foo
}

type C struct{
    Foo map[string]string
}

func(c *C) GetFoo() map[string]string {
    return c.Foo
}

type ABC interface {
    GetFoo() map[string][string]
}

func handleFoo (v ABC){
    foo := v.GetFoo()
    x:=foo["barbie"]
}

推荐阅读