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.
In Go, := is for declaration + assignment, whereas = is for assignment only. For example, var foo int = 10 is the same as foo := 10 .
The := syntax is shorthand for declaring and initializing a variable, example f := "car" is the short form of var f string = "car" The short variable declaration operator( := ) can only be used for declaring local variables.
No. Go has no while statement, only the special form of the for statement - and assignment is a statement, not an expression. Your examples are IMHO idiomatic Go.
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