go - 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"]
}
推荐阅读
- linux - 如何设置电源按钮行为以关闭 linux 中的显示?
- connection - 多个 RD 客户端连接
- identityserver4 - IdentityServer4:Google 登录仅显示 OpenID 范围,不显示电子邮件和个人资料范围信息
- javascript - React Js:.map 不是函数
- android - Android 双向绑定整数类型问题
- react-native - 如何在本机反应中替换图像的 URL
- web - VSCode 的可视化构建器?
- r - 您如何提取与 R 中的主题 ID 列表匹配的行?
- python - googletrans 输入文本未在 tkinter 中读取以进行翻译
- python - 从产品页面获取数据并返回 Scraper