Golang泛型-简单用例 [英] Golang generics - simple use case

查看:491
本文介绍了Golang泛型-简单用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有3种结构:

type A struct{
   Foo map[string]string
}

type B struct{
   Foo map[string]string
}

type C struct{
   Foo map[string]string
}

然后我想创建一个可以接受任何这些结构的函数:

and then I want to create a function that can accept any of those structs:

func handleFoo (){

}

有什么办法可以用Golang做到这一点吗?像这样:

Is there any way to do this with Golang? Something like:

type ABC = A | B | C

func handleFoo(v ABC){
   x: = v.Foo["barbie"] // this would be nice!
}

好的,让我们尝试一个界面:

OK, so let's try an interface:

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之类的属性.

In a language which encourages/forces composition, I cannot understand why you can't access properties like Foo.

推荐答案

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

You can use the interface in this way, add a method GetFoo to get foo of each struct.

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"]
}

这篇关于Golang泛型-简单用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆