Study hard go: 6 Process control

Time:2022-5-6

Learn what

  1. How to use if conditional statements?
  2. How to use switch conditional statements?
  3. Usage switch type?
  4. How to use the for loop statement?
  5. Fallthrough, break, continue, goto usage?

If conditional statement

1. Use format

When “condition judgment” is true, it enters the branch. As follows, when the condition of the first if is judged to be true, enter. Otherwise, continue to judge the else if. If it is still not true, finally enter the else branch.

If [assignment statement;] Conditional judgment{
    //Branch 1
} else If [assignment statement;] Conditional judgment{
    //Branch 2
} else {
    //Branch 3
}

The if statement has the following characteristics:

  • If does not need to be wrapped in parentheses, and the following switch and for statements are the same
  • The assignment statement can be added before the condition judgment, and the condition judgment can be carried out with the result of the assignment

2. No assignment statement

Omitted in “use format”[assignment statement:], only “conditional judgment” is written after if, which is also a format often used in other languages.

num := 10
if num > 12 {
    fmt. Println ("Branch 1")
} else if num > 9 {
    fmt. Println ("branch 2") // if 10 > 9 is true, enter this branch
} else {
    fmt. Println ("branch 3")
}

Conditional judgment is not limited to the above code. The “comparison operator” and “non logical operator” explained in the previous article can participate in judgment, as long as the conditional judgment statement returns bool type.

3. With assignment statement

If the result of “assignment statement” is only used in the current if statement, the following abbreviation can be used.

//Judge function error and print
if err := fun1(); err != nil {
    //The program exits and prints an error
    panic(err)
}

Note: the scope in err in the code is only within the if statement.

Switch conditional statement

1. Use format

Switch statements and if statements are very similar in function, and can basically replace writing, excepttype-switchGrammar, continue to look down will explain.

switch [var1] {
    case: var2
        // todo
    case: var3,var4
        // todo
    default:
        // todo
}

The switch statement has the following characteristics:

  • VAR1 can be any type, assignment statement or omitted.
  • Case can be followed by variable (unlimited number) or judgment statement.
  • After the switch enters the case, only the current case branch is executed by default without writing break.
  • If none of the case branches satisfies the, the default statement will be executed, which is similar to the else branch in the if statement.
  • Use the fallthrough keyword to take the next case branch.
  • The case branch can also be empty and write nothing.

2. Upper code

Example 1: compare num values

num := 1
switch num {
Case 1,2: // enter the branch if the value of num is 1 or 2
    fmt. Println ("1 or 2")
case 3:
    fmt.Println("3")
}

//Output
1 or 2

Example 2: if fallthrough is used, it will be executed even if the next case is not satisfied

num := 1
switch num {
Case 1,2: // enter the branch if the value of num is 1 or 2
    fmt. Println ("1 or 2")
    fallthrough
case 3:
    fmt.Println("3")
}

//Output
1 or 2
3

Example 3: the switch is followed by an assignment statement. Single assignment and multiple assignments in parallel can be used

// flowcontrol/switch.go

switch num1, num2 := 1, 2; {
case num1 >= num2:
    fmt.Println("num1 > num2")
case num1 < num2:
    fmt.Println("num2 < num1")
}

//Output
num2 < num1

Example 4: omit the statement after switch. The following code does not meet all case branches and enters the default branch

num := 3
switch {
case num > 5:
    fmt.Println("num > 5")
case num > 4:
    fmt.Println("num > 4")
case num > 3:
    fmt.Println("num > 3")
default:
    fmt.Println("num <= 3")
}

//Output
num <= 3

Example 5: case branch content is not written

num := 0
switch num {
case 0:
case 1:
    fmt.Println(1)
}

//Entered case 0
//Because there is no content, nothing is output

3. type-switch

It is used to obtain the actual type of the interface (which will be explained later). For different types, judge by branches. If you don’t understand, see the following code.

var data interface{}
data = "111"

//Data is the interface type (type) get the actual type
//Assign the value of the actual type to the D variable
switch d := data.(type) {
case string:
    //After entering the branch, D is of type string
    fmt.Println(d + "str")
case int:
    //After entering the branch, D is of type int
    fmt.Println(d + 1)
}

//Output
111str

Note: passed.(type)Get the actual type of the interface. Remember that this method can only be used in switch statements, which is why I explain it here alone.

For loop statement

For loop statements have two formats in terms of classification. The first is “counter based iteration” and the second is “for range” structure iteration. Next, we will explain these two formats respectively.

1. Counter based iteration

This format is also commonly used in many languages, as follows:

For [initialization statement]; [conditional statement]; [assignment statement]{
        ...
}

//Example: output 0 - 5
for i := 0; i < 6; i++ {
        fmt.Println(i)
}

The for loop statement has the following characteristics:

  • “[initialization statement]”, “[conditional statement]”, “[assignment statement]” can be omitted at will.
  • ”Initialization statement “can be parallel assignment, for example:i, j := 0, 0
  • ”The assignment statement “can assign values in parallel, for example:i, j = i + 1, j + 1

2. Sentence omission

The “initialization statement”, “conditional statement” and “assignment statement” mentioned above can be omitted. That completes a simple example through different ellipsis: “output 0-5 through circular statement”.

Method 1: infinite loop form

i := 0
for {
    fmt.Println(i)
    if i > 4 {
        //Jump out of for loop
        break
    }
    i++
}

Method 2: omit the assignment statement

for i := 0; i < 6; {
    fmt.Println(i)
    i++
}

Method 3: keep only conditional statements

i := 0
for i < 6 {
    fmt.Println(i)
    i++
}

Note: of course, it is not limited to the above three omissions. You can omit one, two and three sentences at will.

3. for-range

for-rangeYou can iterate over any set (array, slice, map), channel, or traverse the string. For the sake of systematization of knowledge points, list these types of formats. If the iterated set and channel are not understood, the following chapters will focus on them.

Iterate array or slice: the two types of iterations are the same,iIndex the subscript,vIs the value of array or slice, which can also be omittedv

for i, v := range collection {
    ...
}

//Omit
for i := range collection {
    ...
}

Iterative mapmapIt is an unordered set of key value pairs (which will be described later),kIs the key name,vIs a value or can be omittedv

for k, v := range collection {
    ...
}

//Omit
for k := range collection {
    ...
}

Iterative channel: get the value from the channel, which will be explained later,vIs a value or can be omittedv

for v := range channel {
    ...
}

//Omit
for range channel {
    ...
}

Iteration string: traverse each character in the string,iIs the position of the character in the string, starting from 0,cEach character in the string can also be omittedc

for i, c := range str {
   ...
}

//Omit
for i := range str {
    ...
}

UTF-8 characters are supported when traversing strings. The code is as follows:

// flowcontrol/for-range-str.go

STR: = "I love China"
for i, c := range str {
    fmt. Printf ("position:% D, character:% C \ n", I, c)
}

//Output
Position: 0, character: me
Position: 3, character: love
Position: 6, character: C
Position: 7, character: H
Position: 8, character: I
Position: 9, character: n
Position: 10, character: a

Several keywords

Come down rightbreakcontinuegotoThese three keywords are explained.

1. break

Break is used in for statements and select statements (which will be later). It means to jump out of the for loop. By default, it jumps out of one layer of loop (without writing the position). You can also specify to jump out of multiple layers of loops (writing the specific jump position). The name of “position” is optional, as long as it does not conflict with the keyword.

[location]
...
break [location]

Example code:

// flowcontrol/break.go

//Jump out of one layer by default: when I is 5, jump out of the loop
for i := 0; i < 10; i++ {
    if i == 5 {
        break
    }
    fmt.Println(i)
}

    //Jump out of specified position: when J is 5, jump out of two-layer cycle
LABEL:
    for i := 0; i < 10; i++ {
        for j := 0; j < 10; j++ {
            if j == 5 {
                //Jump to the label position above 
                break LABEL
            }
            fmt.Println(i)
        }
}

2. contine

Continue is used in the for loop statement, which means that the logic after continue is not executed and directly enters the next loop. If there are multiple for loop statements, you can also specify which loop, and the location can be named arbitrarily.

[location]
...
continue [location]

Example code:

// flowcontrol/continue.go

//Skip inner loop with J = 1 without specifying position
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        if j == 1 {
            fmt. Printf ("% d +% d I don't count \ n", I, J)
            continue
            fmt. Println ("not for me")
        }
        fmt.Printf("%d+%d=%d\n", i, j, i+j)
    }
}

//Output
0+0=0
I didn't count 0 + 1
0+2=2
1+0=1
I didn't count 1 + 1
1+2=3
2+0=2
I didn't count 2 + 1
2+2=4

//Specify the position and skip the outer loop with I = 1
LABEL:
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            if i == 1 {
                fmt. Printf ("% d +% d I don't count \ n", I, J)
                continue LABEL
                fmt. Println ("not for me")
            }
            fmt.Printf("%d+%d=%d\n", i, j, i+j)

//Output
0+0=0
0+1=1
0+2=2
I didn't count 1 + 0
2+0=2
2+1=3
2+2=4

3. goto

In fact, this keyword has nothing to do with “conditional statement” and “circular statement”. It means to directly jump to the specified position and continue to execute logic. The name of the position is arbitrary.

//Jump back
Position 1
...
goto Position 1

//Jump back
Goto position 2
...
Position 2

Example code:

// flowcontrol/goto.go 

     //Jump back. When I is not less than 2, end the jump
   i := 0
UP:
   fmt.Println(i)
   if i < 2 {
      i++
      goto UP
   }

//Output
0
1
2

   //Jump back and skip the logic between goto and down:
   fmt. Println ("you")
   goto DOWN
   fmt. Println ("OK")
DOWN:
   fmt. Println ("ah")

//Output
you
ah

summary

This article explains the usage of “if conditional statement”, “switch conditional statement”, “for loop statement” and keywords “fallthrough, break, continue and goto”, which should be understood. In the process of explanation, it also involves some knowledge points to be talked about later. If you want to know urgently, you can check it first (who makes my article update slow), or leave a message below.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Handsome brother and Miao