Counting Loops
Loop a set number of times with a counter.
1package main
2
3import "fmt"
4
5func main() {
6 for i := 0; i < 5; i++ {
7 fmt.Println(i)
8 }
9}
$ go run main.go
0
1
2
3
4
Every line, explained
package main- Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"- import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func main() {- func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
for i := 0; i < 5; i++ {- The counting flavour of for has three parts separated by semicolons: i := 0 creates the counter, i < 5 keeps looping while true, and i++ adds 1 to i after every trip.
fmt.Println(i)- fmt.Println(...) prints what is inside the brackets to the terminal, then moves to a new line (Println is short for "print line"). The capital P matters: in Go, the tools a package shares all start with a capital letter. Runs five times, printing the current count. Notice it starts at 0, just like slice indexes.
}- This } closes the for loop.
}- This closing brace } ends func main.