来自Nodejs,我可以做如下事情:
// given an array `list` of objects with a field `fruit`:
fruits = list.map(el => el.fruit) # which will return an array of fruit strings
有没有办法在golang用优雅的单尾班轮做到这一点?
我知道我可以用一个量程环路来实现,但我正在寻找一个线性解决方案的可能性
来自Nodejs,我可以做如下事情:
// given an array `list` of objects with a field `fruit`:
fruits = list.map(el => el.fruit) # which will return an array of fruit strings
有没有办法在golang用优雅的单尾班轮做到这一点?
我知道我可以用一个量程环路来实现,但我正在寻找一个线性解决方案的可能性
在Go中,数组是不灵活的(因为它们的长度是用它们的类型编码的),传递给函数的代价很高(因为函数在数组参数的副本上操作).我假设你想在slices而不是数组上操作.
因为methods cannot take additional type arguments,你不能简单地在围棋中声明一个通用的Map
method.但是,您可以将Map
定义为通用top-level function:
func Map[T, U any](ts []T, f func(T) U) []U {
us := make([]U, len(ts))
for i := range ts {
us[i] = f(ts[i])
}
return us
}
然后你可以写下面的代码,
names := []string{"Alice", "Bob", "Carol"}
fmt.Println(Map(names, utf8.RuneCountInString))
打印[5 3 5]
到stdout(在this Playground中试用).
Go 1.18增加了a golang.org/x/exp/slices
package,这为切片提供了许多方便的操作,但明显缺少Map
功能.该功能的省略是GitHub issue中专门讨论golang.org/x/exp/slices
提案的长时间讨论的结果;关注的问题包括:
Map
Russ Cox ultimately Select 从提案中删除Map
,因为它是
作为其他地方更全面的streams API的一部分可能更好.