I am quite new to Go and I already had a few occasions where I would like to use something like a while loop with a short statement (see examples below). Is something like that possible? I am pretty sure there must be some simple way to accomplish this but I was unable to find anything on the internet.
Examples:
(NOTE: I am aware the syntax in these examples isn't supported by Go, I just used the same syntax as in if with a short statement to illustrate my issue)
// pop from queue until it returns nil
for val := queue.Pop(); val != nil {
}
// scan numbers until EOF (enough to check if err is nil for competitive programming)
var n int
for _, err := fmt.Scan(&n); err != nil {
}
CodePudding user response:
There's not syntax for doing exactly what you want, but there's some options for expressing your intention relatively concisely.
Either you move the declaration inside the for loop:
for {
val := queue.Pop()
if val == nil { break }
...
}
Or you duplicate the expression:
for val := queue.Pop(); val != nil; val = queue.Pop() {
...
}
Or you express the loop condition differently (I'm guessing what queue
is here, using len
may not be the right way to find out if the queue is empty or not depending exactly what your queue type is).
for len(queue) > 0 {
val := queue.Pop()
...
}