For Loop in Golang

Golang has the classic version of the for loop with three components separated by semicolons:

ยป More Golang Examples

initial ; condition ; post

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
For Loop in Golang Example

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
	}
}

The output:

$ 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
		}
	}
}

The output:

$ 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)
	}
}

The output:

$ 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/

Golang: https://go.dev/tour/flowcontrol/1