For/Else in Go
Python has a handy for
/else
construction which is useful for avoiding flag variables when searching for things.
1
2
3
4
5
6
for thing in things:
if thing == the_thing_i_want:
break
else:
raise RuntimeError("couldn't find the thing")
# Continue, having found what you were looking for.
It turns out you can replicate this control flow in Go.
1
2
3
4
5
6
7
8
9
10
func run() error {
for _, t := range things {
if t == theThingIWant {
goto found
}
}
return errors.New("couldn't find the thing")
found:
// Continue, having found what you were looking for.
}