for {
value, ok := Func ();
if value == nil {
break;
}
// ... rest of body
}
// analyze "ok" here if needed
Is there a way to avoid the in-body condition/break, and actually use
the for's condition atop?
Thanks, and merry christmas!
That's the pattern - although ok won't be visible outside the loop as
written.
-rob
For your example, try this idiom.
value, ok := commaok()
for value != nil {
// ... rest of value body
value, ok = commaok()
}
if ok == true {
// ... rest of ok body
}
Note that the 2009-12-22 release eliminated most uses of semicolons;
use gofmt to reformat.
release.2009-12-22: http://groups.google.com/group/golang-nuts/msg/ed2c38932ba1bd44
Peter
for {
value, ok := Func ();
if value == nil {
break;
}
// ... rest of body
}
// analyze "ok" here if needed
Is there a way to avoid the in-body condition/break, and actually use
the for's condition atop?
var value int
var ok bool
for value, ok = Func(), value != nil {
// ...
}
though I realize that using the comma token itself can be pretty
ambiguous in this context. (Maybe some *other* token.)
That second comma will not work. The compiler will assume that
'value != nil' is what you are trying to assign to 'ok' and it will
complain that 'Func', which returns two values, is being used in a
single value context. You have to put a semicolon there instead and
follow it with a statement.
var value int;
var ok, bool;
for value, ok = Func (); value != nil; value, ok = Func () {
// ...
}
-Ostsol