Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign-and-compare in go's while-equivalent?

Tags:

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.

like image 364
fluffy Avatar asked Oct 29 '12 18:10

fluffy


People also ask

What is difference between := and in go?

In Go, := is for declaration + assignment, whereas = is for assignment only. For example, var foo int = 10 is the same as foo := 10 .

What does := means in go?

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.


1 Answers

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.

like image 54
zzzz Avatar answered Sep 21 '22 16:09

zzzz