英文:
List comprehension in Go
问题
我有一个结构体数组。
var a = [] struct {
f1 string
f2 string
}{
{"foo", "bar"},
{"biz", "baz"},
}
我想将f2
字段的数组传递给一个函数,像这样
var f2s []string
for _, s := range a {
f2s = append(f2s, s.f2)
}
// f2s = {"bar", "baz"}
SomeFunc(f2s)
有没有更符合惯用方式的方法来做到这一点?在Python中,我会这样做SomeFunc([s.f2 for s in a])
。在函数式语言中,我会这样做(SomeFunc (map (lambda (s) (s.f2)) a))
。
英文:
I have an array of structs.
var a = [] struct {
f1 string
f2 string
}{
{"foo", "bar"},
{"biz", "baz"},
}
I want to pass an array of the f2
fields to a function, like so
var f2s []string
for _, s := range a {
f2s = append.f2s(s.f2)
}
// f2s = {"bar", "baz"}
SomeFunc(f2s)
Is there a more idiomatic way to do this? In Python I would do SomeFunc([s.f2 for s in a])
. In a functional language I would do (SomeFunc (map (lambda (s) (s.f2)) a))
.
答案1
得分: 11
不,Go语言没有列表强制转换或类似的功能。你的代码看起来很好。对于较长的切片,最好使用make函数来分配适当的长度。
英文:
No, Go has no list coercion or that like. Your code looks fine. For longer slices it might be better to allocate the proper length with make.
答案2
得分: 7
不,真诚地说,他们不会。
地图和列表的理解已经足够主流,被认为是任何现代语言中的基础。
这是一种很好的语言,有很多好的想法,但我离感到舒适还有很长的路要走,而且经常感觉我的代码很脏,即使它是按照Go的方式进行的,结构良好的代码。
希望将来会有所改变。
英文:
No, sincerely, they wouldn't.
Maps and lists comprehension is mainstream enough to be considered basic in any modern language.
It's a nice language with great ideas, but I'm still way far from being comfortable, and often times I feel my code is dirty even when it is idiomatic, well structured code in the Go way of doing things.
Hope this changes in the future.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论