“This is the 18th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.”

In many practical problems, there are many regular repeated operations, so some statements need to be repeated in the program.

The Go language provides the following types of looping statements:

Circulation type describe
The for loop Execute the block repeatedly
A nested loop Nested one or more for loops within a for loop

Loop control statement

Loop control statements control the execution of statements inside loops.

The GO language supports the following loop control statements

Circulation type describe
Break statement Often used to break the current for loop or jump out of the switch statement
The continue statement Skip the rest of the current loop and proceed to the next loop
Goto statements Transfers control to the marked statement

1 for(loop structure)

All loop types in the Go language can be done using the for keyword.

The basic format of the for loop is as follows:

forInitial statement; Conditional expression; End statement {loop body statement}Copy the code

The loop body continues to loop until the conditional expression returns false.

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

The initial statement of the for loop can be ignored, but the semicolon after the initial statement must be written, for example:

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

The initial and closing statements of the for loop can be omitted, for example:

func forDemo3(a) {
	i := 0
	for i < 10 {
		fmt.Println(i)
		i++
	}
}

Copy the code

This writing method is similar to while in Java. After while, a conditional expression is added, and the loop continues until the conditional expression is satisfied, otherwise the loop ends.

2 Infinite Loop

The for loop can be forced out of the loop by the break, goto, return, and Panic statements.

for{loop body statement}Copy the code

3 for range(key-value loop)

In Go, range is like an iterator or foreach. You can use for range to iterate over groups, slices, strings, maps, and channels. The return value traversed through for range has the following pattern:

  • Arrays, slicing, and strings return indexes and values.
  • Map returns keys and values.
  • A channel returns only the value within the channel.
We need to write index Ifor key, val := rangecoll { ... } # only the contents of the loop are similar to Java enhancementsforcyclefor _, val := range coll {
    ...
}
Copy the code

Note that val is always copied from the value of the corresponding index in the collection, so it is generally read-only and any changes made to it will not affect the original values in the collection. A string is a unicode-encoded set of characters (or rune), so it can also be used to iterate over strings:

for pos, char := range str {
    ...
}
Copy the code

Practice the multiplication table for loop

// The multiplication table
	fmt.Println("The multiplication table is as follows :")
	for i := 1; i < 10; i++ {
		for j := 1; j <= i; j++ {
			fmt.Printf("%d*%d=%d\t",j,i,i*j)
		}
		fmt.Println()
	}
Copy the code

4 switch case

The switch statement makes it easy to condition a large number of values.

func switchDemo1(a) {
	finger := 3
	switch finger {
	case 1:
		fmt.Println("Thumb")
	case 2:
		fmt.Println("Finger")
	case 3:
		fmt.Println("Middle finger")
	case 4:
		fmt.Println("Ring finger")
	case 5:
		fmt.Println("Little finger")
	default:
		fmt.Println("Invalid input!")}}Copy the code

The Go language specifies that each switch can have only one default branch.

A branch can have multiple values, separated by commas.

func testSwitch3(a) {
	switch n := 7; n {
	case 1.3.5.7.9:
		fmt.Println("Odd")
	case 2.4.6.8:
		fmt.Println("Even")
	default:
		fmt.Println(n)
	}
}
Copy the code

Branching can also use expressions, which do not need to be followed by a variable. Such as:

func switchDemo4(a) {
	age := 30
	switch {
	case age < 25:
		fmt.Println("Study hard.")
	case age > 25 && age < 35:
		fmt.Println("Get back to work.")
	case age > 60:
		fmt.Println("Enjoy it.")
	default:
		fmt.Println("It's good to be alive")}}Copy the code

Fallthrough syntax can execute the next case of a case that meets the condition. It is designed to be compatible with CASES in C language.

func switchDemo5(a) {
	s := "a"
	switch {
	case s == "a":
		fmt.Println("a")
		fallthrough
	case s == "b":
		fmt.Println("b")
	case s == "c":
		fmt.Println("c")
	default:
		fmt.Println("...")}}Copy the code
Output: A, BCopy the code

5 goto(Jump to the specified label)

The GOTO statement makes unconditional jumps between codes through tags. The goto statement can be helpful in breaking out of loops quickly and avoiding repeated exits. The use of goto statements in Go simplifies the implementation of some code. For example, to exit a double-nested for loop:

func gotoDemo1(a) {
	var breakFlag bool
	for i := 0; i < 10; i++ {
		for j := 0; j < 10; j++ {
			if j == 2 {
				// Set the exit label
				breakFlag = true
				break
			}
			fmt.Printf("%v-%v\n", i, j)
		}
		// Outer for loop judgment
		if breakFlag {
			break}}}Copy the code

Using the goto statement simplifies code:

func gotoDemo2(a) {
	for i := 0; i < 10; i++ {
		for j := 0; j < 10; j++ {
			if j == 2 {
				// Set the exit label
				goto breakTag
			}
			fmt.Printf("%v-%v\n", i, j)
		}
	}
	return
	/ / label
breakTag:
	fmt.Println("End for loop")}Copy the code

6 Break (out of loop)

The break statement terminates blocks of code for, switch, and SELECT.

The break statement can also be followed by a label to exit the code block corresponding to a label. The label must be defined on the corresponding for, switch, and SELECT code blocks. Here’s an example:

func breakDemo1(a) {
BREAKDEMO1:
	for i := 0; i < 10; i++ {
		for j := 0; j < 10; j++ {
			if j == 2 {
				break BREAKDEMO1
			}
			fmt.Printf("%v-%v\n", i, j)
		}
	}
	fmt.Println("...")}Copy the code

7 continue(continue the next loop)

The continue statement terminates the current loop and begins the next iteration of the loop. It is only used within the for loop.

When a label is added after the continue statement, the loop for the label begins. Such as:

func continueDemo(a) {
forloop1:
	for i := 0; i < 5; i++ {
		// forloop2:
		for j := 0; j < 5; j++ {
			if i == 2 && j == 2 {
				continue forloop1
			}
			fmt.Printf("%v-%v\n", i, j)
		}
	}
}

Copy the code