In Go you can do:
if foo := bar() ; foo != nil {
...
}
In C/C++ you can do:
while ((foo = bar()) != NULL) {
...
}
However, Go's syntax does not seem to provide any equivalent way of doing assign-and-compare in a while loop; Go has replaced while
with a specific invocation of for
(e.g. for a
is equivalent to for ; a ;
). Simply trying to use the if
version syntax confuses the parser, as it's expecting there to be a third statement.
I could just say:
for foo := bar() ; foo != nil ; foo = bar() {
....
}
but in this case, the bar()
call is fairly long, complex, and not easy to break out into its own function (although I could do something like declaring a local func
to call, but that still reduces the clarity of the code).
For now I am doing:
for {
foo := bar();
if foo == nil { break; }
...
}
but this seems unclean, both because it separates the loop criteria from the loop statement itself, and because it relies on break
.
So, is there a clean, idiomatic way of doing an assign-and-compare in a while loop in Go? This is such a common use case I can't imagine that there's no way of doing it.