04 Program flow control


Program flow control determines how the program is executed. Program control statements generally include: sequence, branch, and loop

Sequence control

The program is executed from top to bottom by default, and there is no jump in the middle.
In Golang, legal forward references are used, and variables must be defined before use (some languages ​​support trial before definition, and the program execution process will be automatically optimized)

Branch control

if branch control

if supports single-branch, double-branch and multi-branch control syntax is as follows

Basic grammar

if 条件表达式1 {
    
    
	执行代码块1
}else if 条件表达式2{
    
    
	执行代码块2
}
....
else{
    
    
    执行代码块3
}

When conditional expression 1 is true, code block 1 will be executed, otherwise conditional expression 2 will be judged, if it is true, code block 2 will be executed, if the previous expressions are all false, code block 3 will be executed

Sample program

func test6(){
    
    
	var age int
	fmt.Println("请输入年龄:")
	fmt.Scanln(&age)
	if(age>18){
    
    
		fmt.Println("你是成年人")
	}else if(age>0){
    
    
		fmt.Println("你是未成年人")
	}else{
    
    
		fmt.Println("年龄不合法")
	}
}

switch branch control

Basic grammar

switch 表达式{
    
    
	case 表达式1,表达式2...:
		代码块1
	case 表达式3,表达式4...:
		代码块2
	...
	default:
	     代码块n	
}     

There is no need to add break in the switch case statement block in go, and there can be multiple expressions after the case separated by commas

Sample code

func test7(){
    
    
	var age int
	fmt.Println("请输入年龄:")
	fmt.Scanln(&age)
	switch age {
    
    
		case 1,2,3,4,5,6:
			fmt.Println("你是儿童")
		case 7,8,9,10,11,12,13,14:
			fmt.Println("你是少年")
		default:
			fmt.Println("你长大了")
	}

	switch  {
    
    
		case 0<age && age<=7:
			fmt.Println("你是儿童")
		case 7<age && age<=14:
			fmt.Println("你是少年")
		default:
			fmt.Println("你长大了")
	}
	switch nage := age; {
    
    
		case 0<nage && nage<=7:
			fmt.Println("你是儿童")
			//fallthrough  switch 穿透
		case 7<nage && nage<=14:
			fmt.Println("你是少年")
		default:
			fmt.Println("你长大了")	
   }

   var x interface{
    
    }
   var y = 10.0
   x = y
   switch i :=x.(type){
    
    
		case nil:
			fmt.Printf("x的类型是 : %T",i)
		case int:
			fmt.Printf("x的类型是 : int")
		case float64:
			fmt.Printf("x的类型是 : float64")
		default:
			fmt.Printf("x的类型是 未知类型")
   } 
}

important point

  1. After case/switch, it can be a variable, expression, or function with a return value.
  2. The data type of the expression after the case must be the same as the type of the expression after the switch
  3. If it is a constant value after the case, it cannot be repeated
  4. default is not required
  5. There can be no expression after switch, similar to if else usage
  6. After the switch can simply declare a variable, a semicolon is not recommended
  7. switch penetration-fallthrough: If fallthrough is added after the case statement block, the next case will continue to be executed
  8. Type Switch: The switch statement can be used in type-switch to determine the type of variable executed by an interface variable

Summary
If there are not many specific values ​​to be judged, and it is suitable for integers, floating-point numbers, characters, and strings, it is recommended to use switch. Brief introduction is efficient.
Other situations: interval judgment, the result is bool type judgment, use if, and if the use range is wider

Loop control

for loop control

Basic grammar

for 循环变量初始化;循环条件;循环变量迭代{
    
    
	循环操作(语句)
}
for ; ; {
    
     //无限循环 通常配合break语句使用
	//操作语句
}
for {
    
    //无限循环 通常配合break语句使用
	//操作语句
}
for index,val := range str{
    
    
	//操作语句
}

Code example

func test8(){
    
    
	for i := 1;i < 10;i++{
    
    
		fmt.Println("结果:",i)
	}
	fmt.Println("=====================")
	var c int =1;
	for {
    
    
		fmt.Println("结果:",c)
		c++
		if(c>10){
    
    
			break
		}
	}
	fmt.Println("=====================")
	var str string = "我爱北京天安门"
	for i :=0 ; i<len(str); i++ {
    
    
		fmt.Printf("%c \n",str[i])
	}
	fmt.Println("=====================")
	for index,val := range str {
    
    
		fmt.Printf("index =%d ,val=%c \n",index,val)
	}
}

while 和 do while

Go language does not have while and do while syntax, you can use for to achieve the same effect.
Code example

func test9(){
    
    

// ---------do while 效果实现
	var c int =1
	for {
    
    
		fmt.Println("结果:",c)
		c++
		if(c>10){
    
    
			break
		}
	}
    // while 效果实现
	for {
    
    
		if(c>10){
    
    
			break
		}
		fmt.Println("结果:",c)
		c++
	}
}

Jump control statement break continue goto return

Break
break is used to suspend the execution of a statement block, and is used to interrupt the current for loop or switch statement

  1. You can use the label to specify which level of the for loop to stop
  2. Jump out of the nearest for loop by default

continue is
used to end this loop and directly start the next loop. When
multiple loops are nested, the label can be used to specify which level of loop to skip

goto

  1. goto can unconditionally make the program go to the specified location for execution
  2. It is usually used in conjunction with conditional statements to realize functions such as conditional transition and out of loop
  3. Generally not recommended to use goto, it is easy to cause chaos

return is
used to jump out of the method or function

Sample code

func test10(){
    
    
	outf://增加标签
	for i := 0;i<5;i++ {
    
    
		inf:
		for j :=0; j<5; j++ {
    
    
			
			fmt.Println("i=",i,",j=",j);
			if i == 1 && j == 2{
    
    
				break inf //结束内存循环 外层循环继续执行  外层继续i =2 的循环
			}

			if i==3 {
    
    
				continue outf
			}

			if i == 5 && j == 2{
    
     // 输出  5 2 后外层循环中止,后续不在有输出
				break outf //结束内存循环
			}
			   
		}
	}
	

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/114385412