Go-Grundlagen
Go for Loops
Go has one loop keyword. See its four forms: counting, while-style, infinite and range.
Das lernst du
- The three-part for
- for as a while loop
- range
for i := 1; i <= 3; i++
1print
2print
3print
4stop
One keyword, four forms
Go has one loop keyword: for. It can count with three parts, repeat while a condition is true, run forever until break, or visit every item with range.
The first loop has a start, a condition and a step. The second has only a condition, like while in other languages. The third has nothing and ends with break. range over a string gives the position and the character of each letter.
Das Wichtigste
- for i := 1; i
<=3; i++ counts. - for condition { } works like while.
- range visits every item.
Ausführbares Go-Beispiel
main.go
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("for:", i)
}
countdown := 3
for countdown > 0 { // a while loop
fmt.Println("while:", countdown)
countdown--
}
total := 0
for { // an infinite loop, left with break
total += 10
if total >= 30 {
break
}
}
fmt.Println("loop result:", total)
for index, letter := range "Go" {
fmt.Println(index, string(letter))
}
}
for: 1
for: 2
for: 3
while: 3
while: 2
while: 1
loop result: 30
0 G
1 oÜben
Öffne das Beispiel im Online-Compiler, ändere einen Wert oder füge eine Zeile hinzu und sage die Ausgabe voraus, bevor du es ausführst. Bring den Code danach absichtlich zum Scheitern und lies die Meldung des Compilers.
Lektion fertig?
Markiere sie als gelernt, um deinen Fortschritt zu verfolgen.
Dein Fortschritt ist in diesem Browser gespeichert Melde dich an, um ihn auf jedem Gerät zu behalten.
Mit einer Challenge üben
Nutze den Inhalt dieser Lektion, um ein echtes Problem zu lösen. Jede Challenge läuft im Browser, mit sofortigen Tests und einem KI-Review.
- Countdown to Liftoff Count down from a number and end with Liftoff! Einfach
- Sum of Odd Numbers Add every odd number up to a limit. Einfach