dqd82461 2013-07-02 00:16 采纳率: 0%
浏览 35
已采纳

Go中的列表理解

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)).

  • 写回答

2条回答 默认 最新

  • dousou2911 2013-07-02 00:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?