if-else statement switch statement

if-else statement

if is a conditional statement. The syntax of the if statement is

if condition {  
}

If conditiontrue, execution {and }code between.

Unlike other languages, such as C language, Go language's { }it is necessary, even if { }only one between the statement.

There are optional if statement else ifand elseparts.

if condition {  
} else if condition {
} else {
}

There can be any number of if-else statements else if. The condition judgment order is from top to bottom. If ifor else ifcondition judgment result is true, the corresponding code block is executed. If no condition is true, the elsecode block is executed.

Let's write a simple program to detect whether a number is odd or even

//if-else
package main

func main() {
	//a:=9
	//1 基本使用
	//if a>10{
	//	fmt.Println("大于10")
	//}else {
	//	fmt.Println("小于等于10")
	//}

	//2 if -else if -else
	//if a>10{
	//	fmt.Println("大于10")
	//}else if a==10 {
	//	fmt.Println("等于10")
	//}else {
	//	fmt.Println("小于10")
	//}

	//3 不能换行(go语言每一行结尾,需要加一个;  ,每当换行,会自动加;)
	//if a>10{
	//	fmt.Println("大于10")
	//}else if a==10 {
	//	fmt.Println("等于10")
	//}else
	//{
	//	fmt.Println("小于10")
	//}

	//4 条件里可以进行初始化操作(有作用域范围的区别)
	//a:=10;
	//if a<10{
	//if a:=10;a<10{
	//	fmt.Println("xxx")
	//}else {
	//	fmt.Println("yyyy")
	//}
	//fmt.Println(a)

	//fmt.Println(a)
}

switch statement

switch is a conditional statement that is used to compare the value of an expression with a list of possible matching options, and execute the corresponding code block based on the match. Alternatively it can be considered more if elsecommon way clause.

Looking at the code is easier to understand than text. Let's start with a simple example, which will take the number of a finger as input and then output the name corresponding to that finger. For example, 0 is the thumb, 1 is the index finger, etc.

//switch
package main

func main() {
	// 1 switch 基本使用
	//a:=10
	//switch a {
	//case 1:
	//	fmt.Println("1")
	//case 2:
	//	fmt.Println(2)
	//case 9:
	//	fmt.Println(9)
	//case 10:
	//	fmt.Println("10")
	//}

	//2 default
	//a:=15
	//switch a {
	//case 1:
	//	fmt.Println("1")
	//case 2:
	//	fmt.Println(2)
	//case 9:
	//	fmt.Println(9)
	//case 10:
	//	fmt.Println("10")
	//default:
	//	fmt.Println("不知道")
	//}

	//3 多条件
	//a:=3
	//switch a {
	//case 1,2,3:
	//	fmt.Println("1")
	//case 4,5,6:
	//	fmt.Println(2)
	//case 7,9:
	//	fmt.Println(9)
	//case 10,16:
	//	fmt.Println("10")
	//default:
	//	fmt.Println("不知道")
	//}


	//4 无表达式
	//a:=3
	//switch  {
	//case a==1 || a==3:
	//	fmt.Println("1")
	//case a==4||a==5:
	//	fmt.Println(2)
	//default:
	//	fmt.Println("不知道")
	//}

	//5 fallthrough,无条件执行下一个case
	//a:=1
	//switch  {
	//case a==1 || a==3:
	//	fmt.Println("1")
	//	//fallthrough  //fallthrough 会无条件执行下一个case
	//case a==4||a==5:
	//	fmt.Println(2)
	//	fallthrough
	//default:
	//	fmt.Println("不知道")
	//}
}



Guess you like

Origin www.cnblogs.com/kai-/p/12747378.html