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))
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With