【发布时间】:2023-01-20 00:44:47
【问题描述】:
Go 中的新功能,找不到任何直观的方法。
我有这样一段代码
tx = getTx()
for _, record := range tx.a {
// do a lot with record.Important
}
for _, record := range tx.b {
// do a lot with record.Important
}
for _, record := range tx.c {
// do a lot with record.Important
}
以及以下结构:
type Record1 struct {
// fields of Record1
Important string
}
type Record2 struct {
// fields of Record1
Important string
}
type TX struct {
a []Record1
b []Record1
c []Record2
}
现在合乎逻辑的是提取每个为了函数逻辑:
func helper(records) { // Here is the problem
// do a lot with record.Important
}
问题:
记录是 []Record1 或 []Record2 类型。但看起来 Golang 中不存在 Union 类型。所以我想我可以将[]string 传递给帮手,但甚至无法找到一种优雅的方式来获得与 map(lambda r: r.Important, tx.a) 等同的东西。没有高阶地图功能,列表理解。我不相信使用原始为了循环来解决这个问题。
【问题讨论】:
-
使用接口或泛型或反射。该语言的名称是“Go”。
-
您应该阅读有关接口和组合的内容。