A while back I have read/seen that you can do a For-Else loop in Go, but now I cannot find the correct syntax anymore. I find it a very useful construct, and would like to have it in my toolbelt.
For a python example of what I mean see http://www.yourownlinux.com/2016/12/python-while-else-loop-break-continue-statement.html .
while myVar <= 10 :
myVar == myNum :
print 'Breaking out of the loop'
break
print 'This number = ' + str(myVar)
myVar += 1
else:
print 'Break statement is executed, printing "else" block'
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" expression ":" suite ["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
Your code:
while myVar <= 10 :
myVar == myNum :
print 'Breaking out of the loop'
break
print 'This number = ' + str(myVar)
myVar += 1
else:
print 'Break statement is executed, printing "else" block'
Your example, in Go,
package main
import (
"fmt"
"strconv"
)
func main() {
var myNum int = 7
var myVar int = 0
for {
if myVar <= 10 {
if myVar == myNum {
fmt.Println("Breaking out of the loop")
break
}
fmt.Println("This number = " + strconv.Itoa(myVar))
myVar++
} else {
fmt.Println(`"while" "else" block`)
break
}
}
}
Playground: https://play.golang.org/p/MkwhWfL4cr6
Output:
This number = 0
This number = 1
This number = 2
This number = 3
This number = 4
This number = 5
This number = 6
Breaking out of the loop