Golang has the classic version of the for loop with three components separated by semicolons:
initial ; condition ; post
package main
import "fmt"
//geekole.com
func main() {
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
package main
import "fmt"
//geekole.com
func main() {
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
package main import "fmt" //geekole.com func main() { for i := 0; i < 10; i++ { fmt.Println(i) } }
The output:
$ go run for_loop.go
0
1
2
3
4
5
6
7
8
9
$ go run for_loop.go
0
1
2
3
4
5
6
7
8
9
$ go run for_loop.go 0 1 2 3 4 5 6 7 8 9
![For Loop in Golang Example](https://geekole.com/wp-content/uploads/2022/06/geekole_for_loop_example_01-1024x349.jpg)
You can use the for loop with a single condition:
package main
import "fmt"
//geekole.com
func main() {
i := 0
for i < 5 {
fmt.Println(i)
i = i + 1
}
}
package main
import "fmt"
//geekole.com
func main() {
i := 0
for i < 5 {
fmt.Println(i)
i = i + 1
}
}
package main import "fmt" //geekole.com func main() { i := 0 for i < 5 { fmt.Println(i) i = i + 1 } }
The output:
$ go run for_loop.go
0
1
2
3
4
$ go run for_loop.go
0
1
2
3
4
$ go run for_loop.go 0 1 2 3 4
Or you can use the for loop with no condition and using a break sentence:
package main
import "fmt"
//geekole.com
func main() {
i := 0
for {
fmt.Println(i)
i = i + 1
if i > 5 {
fmt.Println("break")
break
}
}
}
package main
import "fmt"
//geekole.com
func main() {
i := 0
for {
fmt.Println(i)
i = i + 1
if i > 5 {
fmt.Println("break")
break
}
}
}
package main import "fmt" //geekole.com func main() { i := 0 for { fmt.Println(i) i = i + 1 if i > 5 { fmt.Println("break") break } } }
The output:
$ go run for_loop.go
0
1
2
3
4
5
break
$ go run for_loop.go
0
1
2
3
4
5
break
$ go run for_loop.go 0 1 2 3 4 5 break
And, of course, a for loop can include a continue statement, which will skip the rest of the code block within the for loop.
package main
import "fmt"
//geekole.com
func main() {
for i := 0; i < 10; i++ {
if i < 5 {
continue
}
fmt.Println(i)
}
}
package main
import "fmt"
//geekole.com
func main() {
for i := 0; i < 10; i++ {
if i < 5 {
continue
}
fmt.Println(i)
}
}
package main import "fmt" //geekole.com func main() { for i := 0; i < 10; i++ { if i < 5 { continue } fmt.Println(i) } }
The output:
$ go run for_loop.go
5
6
7
8
9
$ go run for_loop.go
5
6
7
8
9
$ go run for_loop.go 5 6 7 8 9
If you have noticed, in golang parentheses are not used in the for loop, but the braces { }
are always required.
Golang examples: https://geekole.com/golang/