有没有办法在 golang 中映射对象数组?
Is there a way to map an array of objects in 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 的优雅的 one liner 中做到这一点?
我知道我可以用一个范围循环来做到这一点,但我正在寻找单线解决方案的可能性
在 Go 中,数组是不灵活的(因为它们的长度是用它们的类型编码的)并且传递给函数的成本很高(因为函数对其数组参数的副本进行操作)。我假设您想在 slices 而不是数组上进行操作。
因为 methods cannot take additional type arguments,你不能简单地在 Go 中声明一个泛型 Map
方法 。但是,您可以将 Map
定义为通用 top-level 函数 :
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]
打印到标准输出(在 this Playground 中尝试)。
Go 1.18 添加了 a golang.org/x/exp/slices
package, which provides many convenient operations on slices, but a Map
function is noticeably absent from it. The omission of that function was the result of a long discussion in the GitHub issue 专用于 golang.org/x/exp/slices
提案;关注点包括以下内容:
- hidden cost (O(n)) of operations behind a one-liner
- uncertainty about error handling inside
Map
- risk of encouraging a style that strays too far from Go's traditional style
Russ Cox ultimately 选择从提案中删除 Map
因为它是
probably better as part of a more comprehensive streams API somewhere else.
来自 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 的优雅的 one liner 中做到这一点?
我知道我可以用一个范围循环来做到这一点,但我正在寻找单线解决方案的可能性
在 Go 中,数组是不灵活的(因为它们的长度是用它们的类型编码的)并且传递给函数的成本很高(因为函数对其数组参数的副本进行操作)。我假设您想在 slices 而不是数组上进行操作。
因为 methods cannot take additional type arguments,你不能简单地在 Go 中声明一个泛型 Map
方法 。但是,您可以将 Map
定义为通用 top-level 函数 :
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]
打印到标准输出(在 this Playground 中尝试)。
Go 1.18 添加了 a golang.org/x/exp/slices
package, which provides many convenient operations on slices, but a Map
function is noticeably absent from it. The omission of that function was the result of a long discussion in the GitHub issue 专用于 golang.org/x/exp/slices
提案;关注点包括以下内容:
- hidden cost (O(n)) of operations behind a one-liner
- uncertainty about error handling inside
Map
- risk of encouraging a style that strays too far from Go's traditional style
Russ Cox ultimately 选择从提案中删除 Map
因为它是
probably better as part of a more comprehensive streams API somewhere else.