当前位置:网站首页>Go language basic conditional statement if

Go language basic conditional statement if

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

if It's a conditional statement .if The syntax of the sentence is

if condition {  
/*  stay condition by  true  When the  */
}

This is a single conditional statement ,condition by true when , Execute the code in the condition

if condition {
   /*  stay condition by  true  When the  */
} else {
  /*  stay condition by  false  When the  */
}

If condition by true when , Execute above { Code } Code between , If false when , perform else Code inside

if condition 1 {
   /*  stay condition1 by  true  When the  */
} else if condition 2 {
  /*  stay condition2 by  true  When the  */
}else {
/*  stay condition1 and condition2 All for  false  When the  */
}

The order of condition judgment is from top to bottom . If if or else if The result of conditional judgment is true , Then execute the corresponding code block . If no condition is true , be else The code block is executed .

if condition 1 {
   /* condition 1  by  true  When the  */
   if condition 2 {
      /* condition 2  by  true  When the  */
   }
}

This statement only satisfies the condition 1, Then the condition will be carried out 2 The judgment of the , If the condition 1 Are not satisfied , Will not judge the conditions 2

  • else The statement should be in if Braces for statements } In the same line after that . If not , The compiler will not pass .
package main

import "fmt"

func test1() {
	// if Conditions only make judgments 
	num := 10
	if num >= 0 && num < 10 {
		fmt.Println("0 <= num<10")
	} else if num >= 10 && num < 20 {
		fmt.Println("10<= num <20")
	} else {
		fmt.Println("num  be not in 0~20 Between ")
	}
}

func test2() {
	// if The condition is assigned first , And then make a judgment 
	if num := 10; num >= 0 && num < 10 {
		fmt.Println("0 <= num<10")
	} else if num >= 10 && num < 20 {
		fmt.Println("10<= num <20")
	} else {
		fmt.Println("num  be not in 0~20 Between ")
	}
}

func main() {
	test1()
	test2()
}

these two items. test The running result of is the same , But these two test Inside num The scope of is different ,test1 Inside num The scope of is the whole test1,test2 Inside num Only in if The conditions take effect

原网站

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