03 Control Structures the Ins and Outs of If, For, Switch Statements

03 Control Structures - The Ins and Outs of if, for, switch Statements #

In the previous lesson, I gave you a thinking question about searching for one string within another string. This is actually the functionality of string searching. For example, if I need to search for “飞雪” within the string “飞雪无情”, I can do the following:

i:=strings.Index("飞雪无情","飞雪")

This is a common function provided by the Go standard library for us to use, which reduces development time.

In this lesson, we will continue discussing Go language and focus on the control flow of Go code.

Control flow statements are used to control the execution order of a program, so that your program has logical structure. Generally, control flow statements need to be used in conjunction with various conditions, such as if for condition checks, switch for selection logic, and for for looping. In this lesson, I will provide detailed explanations and demonstration examples of their usage.

The if Conditional Statement #

The if statement is a conditional statement that selects which branch to execute based on the boolean expression: if the expression evaluates to true, the if branch is executed; if the expression evaluates to false, the else branch is executed. Let’s take a look at an example of an if conditional statement:

ch03/main.go

func main() {

    i:=10

    if i >10 {

        fmt.Println("i>10")

    } else {

        fmt.Println("i<=10")

    }

}

This is a very simple if…else conditional statement. When i>10 is true, the if branch is executed; otherwise, the else branch is executed. You can run this code yourself to verify the print result.

There are some rules for using if conditional statements:

  1. The condition expression after if does not need to be enclosed in parentheses (), which is different from some other programming languages and highlights the simplicity of the Go language.
  2. The curly braces {} are required for each branch (if or else), even if there is only one line of code inside the curly braces (as shown in the example).
  3. The opening curly brace { immediately following if cannot be on its own line, and the closing curly brace } before else cannot be on its own line, otherwise the code will not compile.
  4. Multiple else if can be added in an if…else conditional statement to increase the number of conditional branches.

By running the code go run ch03/main.go, you will see that the output is “i<=10”, indicating that the if branch is executed.

ch03/main.go

func main() {

    i:=6

    if i >10 {

        fmt.Println("i>10")

    } else if  i>5 && i<=10 {

        fmt.Println("5<i<=10")

    } else {

        fmt.Println("i<=5")

    }

}

You can modify the initial value of i to verify the execution of other branches.

You can also add more else if branches to increase the number of conditional branches, but this approach is not recommended because it reduces code readability. Multiple conditional branches can be replaced with the switch statement that I will discuss later, making the code more concise.

Unlike other programming languages, in the if statement of Go, a simple expression statement can be used, and the statement is separated from the conditional statement by a semicolon (;). With the same example as above, I have refactored it using this approach, as shown in the code below:

ch03/main.go

func main() {

    if i:=6; i >10 {

        fmt.Println("i>10")

    } else if  i>5 && i<=10 {

        fmt.Println("5<i<=10")

    } else {

        fmt.Println("i<=5")

    }

}

After the if keyword and before the i>10 conditional statement, the code i:=6 is used to initialize i, which is separated by a semicolon (;). This simple statement is mainly used to do some initialization work before the if conditional is evaluated. You will notice that the output is the same.

The variable declared by the if simple statement can only be used within the entire if…else if…else conditional statement, such as the variable i in the above example.

The switch Selection Statement #

The if conditional statement is more suitable for cases with fewer branches. If there are many branches, using switch would be more convenient. For example, after refactoring the example above using switch, the code would look like this:

ch03/main.go

switch i:=6;{
case i>10:
    fmt.Println("i>10")
case i>5 && i<=10:
    fmt.Println("5<i<=10")
default:
    fmt.Println("i<=5")
}

The switch statement can also use a simple statement for initialization, which is separated by a semicolon (;). Each case represents a branch, and the branch is executed only when its condition is true. The condition expression after the case branch does not need to be enclosed in parentheses ().

In Go, the switch statement evaluates each case from top to bottom, and once a case is satisfied, the corresponding branch is immediately executed and returned, and the remaining branches will not be evaluated. This means that by default, the case in Go’s switch statement automatically includes a break. This is different from other programming languages, where a clear break is required in the case branch to exit a case. This design in Go language is to prevent the next case from being executed when a break is forgotten.

So what should you do if you really need to execute the immediately following case? Go language has also taken this into consideration and provides the fallthrough keyword. Let’s look at an example with the code below:

ch03/main.go

switch j := 1; j {

case 1:

    fallthrough

case 2:

    fmt.Println("1")

default:

    fmt.Println("No match")

}

The above example will output 1. If the fallthrough after case 1 is omitted, there will be no output.

You may notice that, compared to the previous example, this example has an expression after switch, which is ;j as the input. In the previous example, there was only a simple statement used for initialization after switch.

When there is an expression after switch, the values after case must be of the same type as the result type of the expression. For example, in this case, j is of type int, so only int types can be used after case, such as case 1, case 2 in the example. If other types are used, such as case "a", it will prompt a type mismatch and cannot be compiled.

For the case where the expression is omitted after switch, the entire switch structure is equivalent to conditional statements like if...else.

There are no strict restrictions on the expression after switch, as long as it is a valid expression, and it does not have to be a constant or an integer. You can even put the comparison expression directly after switch, as shown in the code below:

```go
switch 2 > 1 {

case true:

    fmt.Println("2 > 1")

case false:

    fmt.Println("2 <= 1")

}

As you can see, the switch statement in the Go language is very powerful and flexible.

for Loop Statement #

When calculating the sum of numbers from 1 to 100, it would be very complicated and not readable if you add up each number using code. This is where the value of the loop statement comes into play.

Here is a classic for loop example. From this example, we can analyze that the for loop consists of three parts, which are separated by two semicolons, as shown below:

sum := 0

for i := 1; i <= 100; i++ {

    sum += i

}

fmt.Println("the sum is", sum)

Here:

  1. The first part is a simple statement, generally used for initializing the for loop. For example, a variable is declared here and initialized with i := 1.
  2. The second part is the condition of the for loop, which means when the for loop ends. The condition here is i <= 100.
  3. The third part is the update statement, generally used for updating the loop variable. For example, i++ is used here to achieve the purpose of incrementing the loop variable.

It should be noted that the for loop in the Go language is very powerful. None of the three parts mentioned above are required and can be omitted. Now I will demonstrate the effect after omitting the above three parts.

If you have learned other programming languages before, you may have seen loop statements like while. In the Go language, there is no while loop, but you can achieve the effect of while using for, as shown in the code below:

sum := 0

i := 1

for i <= 100 {

    sum += i

    i++

}

fmt.Println("the sum is", sum)

This example has the same effect as the previous for example, but there is only one conditional statement i <= 100 after for here, which means that it achieves the effect of while.

In the Go language, you can also use continue and break to control the for loop:

  1. continue can skip the current iteration and continue with the next iteration.
  2. break can exit the entire for loop, even if the for loop has not finished executing, it will force termination.

Now let me modify the previous example of calculating the sum of integers within 100 to demonstrate the use of break, as shown in the code below:

sum := 0

i := 1

for {

    sum += i

    i++

    if i > 100 {

        break

    }

}

fmt.Println("the sum is", sum)

This example uses a for loop with no conditions, also known as an infinite loop. In addition, break is used to exit the infinite loop, with the condition i > 100.

Summary #

This lesson mainly explains the basic usage of control statements such as if, for, and switch. By using them, you can better control the logical structure of the program and achieve the goals of the business requirements.

The exercise for this lesson is to give an example and practice using continue in the for loop.

The control statements provided by the Go language are very powerful. I did not introduce all of them in this lesson, such as type selection in the switch statement and for range in the for loop statement. I will introduce these advanced features one by one in the subsequent lessons. Next, I will explain in detail how to use for range to iterate over collections. Remember to attend the class!