当前位置: > > > > Golang 泛型 – 简单用例
Golang 泛型 – 简单用例
来源:stackoverflow
2024-05-01 08:54:33
0浏览
收藏
大家好,今天本人给大家带来文章《Golang 泛型 – 简单用例》,文中内容主要涉及到,如果你对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 这样的属性。
解决方案
可以这样使用接口,添加一个方法 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"]
}
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注米云公众号,一起学习编程~
