I'm attempting to port some C to Go.
I'm essentially looking for something in Go akin to Haskell's find :: (a -> Bool) -> [a] -> Maybe a
I have (roughly) this C for finding an item in a "list" by iterating through it:
struct foo {
struct foo *next;
char *name;
}
struct foo *foo_list;
// Snip
struct foo *foo = NULL;
for (f = foo_list; f; f = f->next) {
if (!strcmp("bar", f->name) {
foo = f;
}
}
if (foo)
// Stuff
How can I do this nicely and idiomatically in Go?
The "list" is likely to be small; performance characteristics aren't particularly interesting.
Am I likely to want a slice
, or a list
? A "list" of Foo
s or *Foo
s?
I currently have the following, but I suspect it's not particularly "idiomatic Go"!
var FooTable *list.List
// Snip
var foo *Foo = nil
for e := FooTable.Front(); e != nil; e = e.Next() {
if e.Value.(*Foo).name == "bar" {
foo = e.Value.(*Foo)
break
}
}