当前位置:网站首页>Introduction to go language (VI) -- loop statement

Introduction to go language (VI) -- loop statement

2022-06-11 19:10:00 AI Xing

Three forms of loop statements

And C、java、python The difference is GO There is only for Loop statement , however Go Of for Circular statements can also be used in other languages while The function of sentences
Here are three for The use of recycling

routine for loop

for i:= Initial value ; i <=  Termination value ; i++ {
    
	// Code block 
}

act as while Of for loop

i:= Initial value 
for i <  End value  {
    
	//  Code block 
	// i Change towards the end value 
}

for And range In combination with

It should be noted that for And range When iterating with, the iteration variables must be of iteration type : Array or dictionary

for idx, value range m {
     // m Is an iteratable variable 
	// Code block 
}

for Loop example

package main

import "fmt"

func main(){
    
	for i:=0; i < 10; i++ {
    
		fmt.Printf("i:%v\n", i)
	}
	fmt.Printf("\n")
	
	i:=0
	for i < 10 {
    
		fmt.Printf("i:%v\n", i)
		i++
	}
	
	var a = []int{
    1, 2, 3, 4, 5}
	for idx, value := range a {
    
		fmt.Printf("idx:%v, value:%v\n", idx, value)
	}
	
	mp:=make(map[int]string, 0)
	mp[0] = "hello"
	mp[1] = "world"
	for key, value := range mp {
    
		fmt.Printf("key:%v, value:%v\n", key, value)
	}
}

 Insert picture description here

End cycle

break

If you write directly in the loop break be break Quit yes break In the cycle ; meanwhile Go Allows us to define a tag before entering a layer loop , Can be in break When you specify a label, you can exit the cycle specified by the label directly

Example

Let's assume that we have two cycles , We are going to find the sum of two cycles 10 To exit the loop
direct break The situation of

package main

import "fmt"

func main(){
    
	for i:=0; i < 10; i++ {
    
		for j:=0; j < 10; j++ {
    
			fmt.Printf("i:%v, j:%v, sum:%v\n", i, j, i + j)
			if i + j >= 10{
    
				break
			}
		}
	}
}

 Insert picture description here
According to the running results, it does not meet our requirements , Because it's used alone break You can only exit the current break In the cycle
Tagged break

package main

import "fmt"

func main(){
    	
	ENDLABEL:
	for i:=0; i < 10; i++ {
    
		for j:=0; j < 10; j++ {
    
			fmt.Printf("i:%v, j:%v, sum:%v\n", i, j, i + j)
			if i + j >= 10{
    
				break ENDLABEL
			}
		}
	}
	
}

 Insert picture description here

continue

continue The basic definition of is no different from other languages , And break equally , It can also define a tag , direct continue Loop under label

原网站

版权声明
本文为[AI Xing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111906014179.html