Table of contents
Conditional statements require developers to specify one or more conditions, and determine whether to execute the specified statement by testing whether the condition is true, and execute another statement if the condition is false.
The Go language provides the following conditional judgment statements:
statement | describe |
---|---|
if statement | An if statement consists of a Boolean expression followed by one or more statements. |
if…else statement | An optional else statement can be used after the if statement, the expression in the else statement is executed when the boolean expression is false. |
if nested statement | You can embed one or more if or else if statements within an if or else if statement. |
switch statement | The switch statement is used to perform different actions based on different conditions. |
select statement | The select statement is similar to the switch statement, but select executes a random runnable case. If there are no cases to run, it blocks until there are cases to run. |
1. if conditional statement
An if statement consists of a Boolean expression followed by one or more statements.
The syntax of an if statement in the Go programming language is as follows:
if boolean expression { /*Executed when boolean expression is true*/ }
//Pass the test results, send a notebook, and output the test results package main import "fmt" //Score of at least 60 points func main() { var source = 80 if source >= 60 { fmt.Println("Give away a notebook!") } fmt.Println("The test scores are:", source) } //The output is as follows Give away a notebook! The test score is: 80
2. if...else statement
An optional else statement can be used after the if statement, the expression in the else statement is executed when the boolean expression is false
The syntax of an if…else statement in the Go programming language is as follows:
if boolean expression { /*Executed when boolean expression is true*/ }else { /*Executed when boolean expression is false*/ }
//If the test score is higher than 60, it will be considered a pass, and a notebook will be given; if the test score is lower than 60, it will be penalized for copying; and the test score will be output. package main import "fmt" func main() { var source = 98 if source >= 60 { fmt.Println("Give away a notebook!") } else { fmt.Println("Punishment!") } fmt.Println("The test scores are:", source) } //The output is as follows Give away a notebook! The test score is: 98
3, if statement nesting
You can embed one or more if or else if statements within an if or else if statement
The syntax of an if…else statement is as follows:
if boolean expression 1 { /*Executed when boolean expression 1 is true*/ if boolean expression 2 { /*Executed when boolean expression 2 is true*/ } }
//The school holds a track and field competition, and the finals are entered within 10 seconds; after the finals are divided into male and female groups according to gender package main import "fmt" func main() { var ( sec = 8.8 sex = "boy" ) if sec < 10 { fmt.Println("Congrats on reaching the finals!") if sex == "boy" { fmt.Println("You are in the men's group") } else { fmt.Println("You are in the women's group") } } else { fmt.Println("You are eliminated! Please try your best next time!") } } //The output is as follows Congrats on reaching the finals! You are in the men's group
4. switch branch
The switch statement is used to perform different actions based on different conditions. Each case branch is unique and tested one by one from top to bottom until it matches
The switch statement executes from top to bottom until a match is found, and there is no need to add break after the match
By default, switch has a break statement at the end of the case. After the match is successful, no other case will be executed. If we need to execute the latter case, we can use fallthrouth
The syntax of the switch statement is as follows:
switch var1 { case val1: ... case val2: ... default: ... }
The variable var1 can be of any type, and val1 and val2 can be any value of the same type. The type is not limited to constants or integers, but must be of the same type; or the final result is an expression of the same type
//Switch statement with multiple conditions //The grades will be assessed on the student's performance, 90-100: excellent; 80-89: good; 60-79 pass; below 60 fail. package main import "fmt" func main() { var source = 77 //Equivalent to if...else if multi-branch statement switch { case source >= 90 && source <= 100: fmt.Println("excellent") case source >= 80 && source <= 89: fmt.Println("good") case source >= 60 && source <= 79: fmt.Println("qualified") default: fmt.Println("Failed") } }
package main import "fmt" func main() { var vaule = 2 switch vaule { case 1: fmt.Println("Menu 1 function") case 2: fmt.Println("Menu 2 function") case 3: fmt.Println("Menu 3 function") default: fmt.Println("Input errors, please re-enter!") } } //The input result is as follows Menu 2 function
5,Type Switch
The switch statement can also be used in type-switch to determine the type of variable actually stored in an interface variable
The syntax of Type Switch is as follows:
switch x.(type){ case type: statement(s); case type: statement(s); //You can define any number of case s default: /* optional */ statement(s); }
package main import "fmt" func main() { //define empty interface var x interface{} //Determine the data type switch i := x.(type) { case nil: fmt.Printf("data type is%T", i) case int: fmt.Println("data type is int") case float32, float64: fmt.Println("data type is float") case string: fmt.Println("data type is string") case bool: fmt.Println("data type is boolean") default: fmt.Println("data type is other type") } } //The output is: data type is<nil>
package main import "fmt" // Global variables can not be called, variables declared in functions must be called func main() { var num = 10 make_type(number) } //Define the judgment data type func make_type(x interface{}) { // Judging the data type type can only be used with Switch, if you want to use the output data type alone, you need to use reflection switch i := x.(type) { case nil: fmt.Printf("The data type is %T",i) case int: fmt.Println("The data type is int") case float32,float64: fmt.Println("data type is float") case string: fmt.Println("data type is string") case bool: fmt.Println("The data type is bool") default: fmt.Println("other types") } } //The output is: data type is integer
//Reflection determines the data type, which is more flexible package main import ( "fmt" "reflect" ) func main() { var num *int fmt.Println("num data type:",reflect.TypeOf(num)) } //The output is: num data type: *int
6,fallthrough
fallthrough will enforce the execution of the following case statement, fallthrough will not judge whether the expression result of the next case is true
package main import "fmt" func main() { switch { case false: fmt.Println("1,case The conditional statement is false") fallthrough case true: fmt.Println("2,case The conditional statement is true") fallthrough case false: fmt.Println("3,case The conditional statement is false") fallthrough case true: fmt.Println("4,case The conditional statement is true") case false: fmt.Println("5,case The conditional statement is false") fallthrough default: fmt.Println("6,default case") } } //The output is: 2,case The conditional statement is true 3,case The conditional statement is false 4,case The conditional statement is true
7. select statement
select is a control structure in Go, similar to a switch statement for communication. Each case must be a communication operation, either send or receive
select executes a runnable case at random. If there are no cases to run, it blocks until there are cases to run. A default clause should always be runnable
select { case communication clause : statement(s); case communication clause : statement(s); /* You can define any number of case s */ default : /* optional */ statement(s); }
The following describes the syntax of the selcet statement:
Each case must be a communication.
All channel expressions are evaluated.
All expressions sent are evaluated.
If any communication is possible, it is executed, the others are ignored.
If more than one case can be run, Select will randomly and fairly pick one to execute. Others will not execute.
otherwise:
If there is a default clause, the statement is executed.
Without a default clause, select will block until some communication can run; Go will not re-evaluate the channel or value.
package main import "fmt" func main() { var c1, c2, c3 chan int var i1, i2 int select { case i1 = <-c1: fmt.Printf("received ", i1, " from c1\n") case c2 <- i2: fmt.Printf("sent ", i2, " to c2\n") case i3, ok := (<-c3): // same as: i3, ok := <-c3 if ok { fmt.Printf("received ", i3, " from c3\n") } else { fmt.Printf("c3 is closed\n") } default: fmt.Printf("no communication\n") } } //Output result: no communication
package main import ( "fmt" "time" ) func Chann(ch chan int, stopCh chan bool) { for j := 0; j < 10; j++ { ch <- j time.Sleep(time.Second) } stopCh <- true } func main() { ch := make(chan int) c := 0 stopCh := make(chan bool) go Chann(ch, stopCh) for { select { case c = <-ch: fmt.Println("Receive C", c) case s := <-ch: fmt.Println("Receive S", s) case _ = <-stopCh: goto end } } end: } //The output is: Receive S 0 Receive C 1 Receive S 2 Receive S 3 Receive C 4 Receive S 5 Receive S 6 Receive S 7 Receive C 8 Receive S 9