当前位置:网站首页>For loop of go language foundation

For loop of go language foundation

2022-06-23 07:52:00 Ink purple feather ink

One 、 Loop statement

Loop statements are used to repeatedly execute a piece of code .

for yes Go The only loop statement in language .

Go Linguistic For Circulatory 3 In the form of , Only one of them uses semicolons .

for init; condition; post { }

for condition { }

for { }

init: It's usually an assignment expression , Assign initial values to control variables ; condition: A relational or logical expression , Cycle control conditions ; post: It's usually an assignment expression , Increment or decrement of a control variable . for The execution of the statement is as follows :

  1. Let's start with the expression init Assign initial value to ;
  2. Discriminating assignment expression init Whether the given condition Conditions , If the value is true , Satisfy the cyclic condition , Then execute the statement inside the loop , And then execute post, Enter the second loop , Judge again condition; Otherwise, judgment condition The value of is false , Not meeting the conditions , On termination for loop , Execute the out of loop statement .

and if Conditional statements are the same , Loop statements can also be nested

for [condition |  ( init; condition; increment ) | Range]
{
   for [condition |  ( init; condition; increment ) | Range]
   {
      statement(s)
   }
   statement(s)
}

Two 、 Cycle control

  1. break Statement is used to terminate abruptly before completing normal execution for loop , Then the program will be in for The next line of the loop starts executing .
  2. continue Statements are used to jump out of for The current loop in the loop . stay continue All after the statement for Loop statements are not executed in this loop . The loop will continue to execute in the next loop .

3、 ... and 、 Example

package main

import "fmt"

func test1() {
	//  normal for loop 
	for i := 0; i < 3; i++ {
		fmt.Printf("i=%d\t", i)
	}
}

func test2() {
	//  Anamorphic writing 
	i := 0
	for i < 3 {
		fmt.Printf("i=%d\t", i)
		i = i + 1
	}

}

func main() {
	test1()
	fmt.Println()
	test2()
}

Four 、 Infinite loop

func test3() {
	for true {
		fmt.Println("Hello World")
	}
}

//  Or just put true Also omitted 
func test3() {
	for {
		fmt.Println("Hello World")
	}
}

tip : Infinite loop careful use ,Ctrl+c You can stop the examples in this article .

原网站

版权声明
本文为[Ink purple feather ink]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201122252497964.html