In this article, you’ll learn the flow control statements for Go: for, if, ELSE, switch, and defer

§ for

Go has only one loop structure: a for loop.

The basic for loop consists of three parts separated by a semicolon:

  • Initialization statement: Executed before the first iteration
  • Conditional expression, then before and after;Will be removed if: evaluated before each iteration
  • Post statement: Executed at the end of each iteration

The initialization statement is usually a short variable declaration that is visible only in the scope of the for statement.

Once the Boolean value of the conditional expression is false, the loop iteration is terminated.

Note: Unlike languages such as C, Java, and JavaScript, there are no parentheses () around the three components of Go’s for statement, whereas curly braces {} are required.

package main

import "fmt"

func main(a) {
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println(sum)
}
Copy the code

Output:

45
Copy the code

The initialization and postsetting statements are optional, for example:

package main

import "fmt"

func main(a) {
	i := 0
	j := 100
	c := 0
	fori ! = j {// for ; i ! = j; {automatically formatted result, "while" in go
		i++
		j--
		c += 1
	}
	fmt.Printf("i: %v, j: %v, c: %v\n", i, j, c)
}
Copy the code

Output:

i: 50, j: 50, c: 50
Copy the code

If only conditional expressions, before and after; Will be removed by go FMT and become “while” in go. An initialization statement, a conditional expression, or a postposition statement are not omitted.

For is also the “while” of go.

You can drop the semicolon and only write conditional statements in for and {. C’s while in Go is also called for.

package main

import "fmt"

func main(a) {
	s := 1
	for s <= 1000 {
		s += s
	}
	fmt.Println(s)
}
Copy the code

Output:

1024
Copy the code

An infinite loop

If the loop condition is omitted and nothing is written between for and {, the loop will not end, so the infinite loop can be written compact. (For without conditions is the same as for true.)

package main

import (
	"fmt"
	"time"
)

func main(a) {
	i := 0
	for {
		fmt.Println(i)
		i++
		time.Sleep(100 * time.Millisecond)  // Pause 100 mm}}Copy the code

Output:

0 1 2... // Omit part of the output ^Csignal: interrupt // Type control+C to terminate the programCopy the code

§ if

Go’s if statement is similar to a for loop in that there are no parentheses () outside the expression, but curly braces {} are required.

package main

import (
	"fmt"
	"math"
)

func sqrt(x float64) string {
	if x < 0 {
		return sqrt(-x) + "i"
	}
	return fmt.Sprint(math.Sqrt(x))
}

func main(a) {
	fmt.Println(sqrt(2), sqrt(4 -))}Copy the code

Output:

1.4142135623730951 2 ICopy the code

The short statement of if

Like for, an if statement can execute a simple statement before a conditional expression.

This statement declares variables that are scoped only within if.

(Use v at the end of the return statement.)

package main

import (
	"fmt"
	"math"
)

func pow(x, n, lim float64) float64 {
	if v := math.Pow(x, n); v < lim {
		return v
	}
	return lim
}

func main(a) {
	fmt.Println(
		pow(3.2.10),
		pow(3.3.20),)}Copy the code

Output:

September 20Copy the code

if-else

package main

import (
	"fmt"
	"math"
)

func pow(x, n, lim float64) float64 {
	if v := math.Pow(x, n); v < lim {
		return v
	} else {
		fmt.Printf("%g >= %g\n", v, lim)
	}
	// We can't start with v
	return lim
}

func main(a) {
	fmt.Println(
		pow(3.2.10),
		pow(3.3.20),)}Copy the code

Output:

27 >= 20
9 20
Copy the code

Variables declared in the if short statement can also be used in any corresponding else block.

(Both calls to POw are executed and return their respective results before main’s fmt.println call begins.)

§ switch

Switch is an easy way to write a series of if-else statements. It runs a case statement whose first value is equal to the condition expression.

The switch statement in Go is similar to that in C, C++, Java, JavaScript, and PHP, except that Go only runs the selected case, not all subsequent cases. In fact, Go automatically provides the break statement required after each case in these languages. The branch terminates automatically unless terminated by a fallthrough statement. Another important difference with Go is that the case of switch does not have to be constant and the value does not have to be an integer.

package main

import (
	"fmt"
	"runtime"
)

func main(a) {
	fmt.Print("Go runs on ")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}
Copy the code

Output:

Go runs on OS X.
Copy the code

Evaluation order of the switch

Case statements of switch are executed from top to bottom until the match is successful.

(e.g.,

switch i {
case 0:
case f():
}
Copy the code

F is not called when I ==0.

package main

import (
	"fmt"
	"time"
)

func main(a) {
	fmt.Println("When's Saturday?")
	today := time.Now().Weekday()
	switch time.Saturday {
	case today + 0:
		fmt.Println("Today.")
	case today + 1:
		fmt.Println("Tomorrow.")
	case today + 2:
		fmt.Println("In two days.")
	default:
		fmt.Println("Too far away.")}}Copy the code

Output:

When's Saturday?
Tomorrow.
Copy the code

No conditional switch

A switch without a condition is the same as switch true.

This form makes a long list of if-then-else’s clearer.

package main

import (
	"fmt"
	"time"
)

func main(a) {
	t := time.Now()
	switch {
	case t.Hour() < 12:
		fmt.Println("Good morning!")
	case t.Hour() < 17:
		fmt.Println("Good afternoon.")
	default:
		fmt.Println("Good evening.")}}Copy the code

Output:

Good evening.
Copy the code

§ defer

The defer statement will defer the function until after the outer function returns.

The arguments to a delayed function are evaluated immediately (closure? 🤔️), but the function is not called until the outer function returns.

package main

import "fmt"

func main(a) {
	defer fmt.Println("world")

	fmt.Println("hello")}Copy the code

Output:

hello
world
Copy the code

Defer the stack

Deferred function calls are pushed onto a stack. When the outer function returns, the delayed functions are called in last in, first out order.

For more information on the Defer statement, see this article.

package main

import "fmt"

func main(a) {
	fmt.Println("counting...")

	for i := 0; i < 10; i++ {
		defer fmt.Println(i)
	}

	fmt.Println("done.")}Copy the code

Output:

counting...
done.
9
8
7
6
5
4
3
2
1
0
Copy the code