This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

Let’s move on to golang branch statements. Branch statements include if statements, switch statements, select statements, and so on.

There are three kinds of process control structures:

Sequential structure: executes line by line from top to bottom.

Select structure: Some code will be executed only if the condition is met.

Branch statements: if, switch, select

Loop structure: If a condition is met, some code will be executed more than once.

If statement

Syntax format:

/* If the condition is true, then the block in curly braces is executed; If false, the block in braces is not executed. * /
Copy the code

Example code:

func main(a) {
  
    var score int

    fmt.Printf("Please enter your score :>>>")
    fmt.Scan(&score)

    if score >= 60 {
        fmt.Println("Congratulations, you've passed.")}}Copy the code

In addition to the above simple single-logical if judgment, there are the following:

if bool {
   /* Execute */ when the Boolean expression bool is true
} else {  // Note that the else at this position cannot wrap lines
  /* Execute */ when the Boolean expression bool is false
}

if bool {
   /* Execute */ when the Boolean expression bool is true
} else if bool{
   /* execute */ when the Boolean expression bool is false and bool is true
} else{
   /* If both Boolean expressions are false, execute */
}
Copy the code

Golang also supports several variations of if in if statements. Let’s take a look at these:

if statement; condition {  
}

if condition{
       
}
Copy the code

Here’s an example: num is defined in if, then only in if.. Else statement block

func main(a) {  
    if num := 10; num % 2= =0 { 
        fmt.Println(num,"is even")}else {
        fmt.Println(num,"is odd")}}Copy the code

A switch statement

Switch is a conditional statement that evaluates the expression, compares it to a list of possible matches, and executes a block of code based on the match. It can be thought of as an idiomatic way to write multiple if else clauses.

The switch statement tests from top to bottom until it matches. The switch statement executes from top to bottom until a match is found, and no break is required after the match. In Go, switch is equivalent to each case with break at the end by default. After a successful match, other cases will not be automatically executed downward, but the whole switch will jump out. However, fallthrough can be used to enforce the following case code.

If the switch has no expression, it matches true, and if each case expression evaluates to true, the corresponding block of code is executed.

switch var1 {
    case val1:
        ...
    case val2:
        ...
    default:... }Copy the code
var str = "Hel // base usage switch STR {case"good": fmt.Println("Good morning")
case "hello": fmt.Println("hello everyone") default: fmt.Println(".")}Copy the code

fallthrough

Add fallthrough if subsequent cases are needed

package main

import (
	"fmt"
)

type data [2]int

func main(a) {
	switch x := 5; x {
	default:
		fmt.Println(x)
	case 5:
		x += 10
		fmt.Println(x)
		fallthrough
	case 6:
		x += 20
		fmt.Println(x)

	}

}
Copy the code

Running result:

15
35
Copy the code

Precautions for switch

  1. The constant value after case must be unique
  2. You can have multiple constant values after case
  3. Fallthrough should be the last line of a case. If it appears somewhere in the middle, the compiler will throw an error.

Type Switch

The switch statement can also be used with type-switch to determine what type of variable is actually stored in an interface variable.

switch x.(type) {case type:
       statement(s);      
    case type:
       statement(s); 
    
    default: 
       statement(s);
}

package main

import "fmt"

func main(a) {
   var x interface{}
     
   switch i := x.(type) {
      case nil:	  
         fmt.Printf("Type of x :%T",i)                
      case int:	  
         fmt.Printf("X is an int")                       
      case float64:
         fmt.Printf("X is type float64")           
      case func(int) float64:
         fmt.Printf("X is func(int)")                      
      case bool.string:
         fmt.Printf("X is a bool or string" )       
      default:
         fmt.Printf("Unknown type")}}Copy the code