Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension in Go

Tags:

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

like image 239
Nick Garvey Avatar asked Jul 02 '13 00:07

Nick Garvey


2 Answers

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.

like image 59
Volker Avatar answered Nov 14 '22 13:11

Volker


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.

like image 37
Rha7 Avatar answered Nov 14 '22 15:11

Rha7