12.Loop - Init, Condition, Post- Programming in GO

Posted on Mar 06, 2019   ∣  1 min read  ∣  GO

Loop - Init, Condition, Post

As you’re learning Go, a good quick reference is Go by Example.

For example, here’s what it has for for

package main

import "fmt"

func main() {

	i := 1
	for i <= 3 {
		fmt.Println(i)
		i = i + 1
	}

	for j := 7; j <= 9; j++ {
		fmt.Println(j)
	}

	for n := 0; n <= 5; n++ {
		if n%2 == 0 {
			continue
		}
		fmt.Println(n)
	}
}

Note: There is no while in Go.

The way to create a loop is to start with for, and the first thing you put in is an init statement, a condition, and a post, e.g.

  for init; condition; post {
  }

Let’s try a loop with an init statment initializing a variable i with the value 0, the condition that i is less than or equal to 100, and the post of incrementing i by 1 (i++). Remember, we can always check the Go spec. In this case, IncDec statements has information explaining the ++ and -- operators.

package main

import (
	"fmt"
)

func main() {
	// for init; condition; post {}
	for i := 0; i <= 100; i++ {
		fmt.Println(i)
	}
}

playground