Loops
Last updated
Last updated
For syntax of varPattern
see
break
and continue
are supported
for let <varPattern> = <expr>; <terminal expr>; <expr run after every iteration> {
<loop body>
}
package main
import "fmt" as fmt
fun Unit main() {
fmt.println("Counting to 10...")
for let a = 1; a <= 10; a++ {
fmt.println(a)
}
fmt.println("Done!")
}
package main
import fmt "fmt"
func main() {
fmt.Println("Counting to 10...")
for a := 1; a <= 10; a++ {
fmt.Println(a)
// Eliminates any 'unused variable' errors
_ = a
}
fmt.Println("Done!")
}
Counting to 10...
1
2
3
4
5
6
7
8
9
10
Done!
for let <varPattern> in <iterable> {
<loop body>
}
package main
import "fmt" as fmt
fun Unit main() {
fmt.println("Iterating through every letter in the word 'Hello'")
for let _, c in "Hello" {
fmt.println((String)(c))
}
fmt.println("Done!")
}
package main
import fmt "fmt"
func main() {
fmt.Println("Iterating through every letter in the word 'Hello'")
for _, c := range "Hello" {
fmt.Println(string(c))
// Eliminates any 'unused variable' errors
_ = c
}
fmt.Println("Done!")
}
Iterating through every letter in the word 'Hello'
H
e
l
l
o
Done!
for <terminal expr> {
<loop body>
}
package main
import "fmt" as fmt
fun Unit main() {
fmt.println("The program will terminate if you say the magic word...")
let magicWord = "please"
zero String input
while input != magicWord {
fmt.println("What's the magic word?")
fmt.scan(&input)
}
fmt.println("You said it!")
}
package main
import fmt "fmt"
func main() {
fmt.Println("The program will terminate if you say the magic word...")
magicWord := "please"
var input string
for {
if !(input != magicWord) {
break
}
fmt.Println("What's the magic word?")
fmt.Scan(&input)
}
fmt.Println("You said it!")
// Eliminates any 'unused variable' errors
_, _ = magicWord, input
}
The program will terminate if you say the magic word...
What's the magic word?
Gauntlet
What's the magic word?
Go
What's the magic word?
Life
What's the magic word?
please
You said it!