我有一个结构数组。
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))
.
最佳答案
不,Go 没有列表强制等。你的代码看起来不错。对于较长的 slice ,最好使用 make 分配适当的长度。
关于go - Go 中的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17415567/