If Branch Statement

GoGoBeginner
Practice Now

Introduction

When making a ToDo plan, if an event has not been completed yet, it will be added to the To-Do list, and if it has been completed, it will be moved to the completed items.

In the world of programming, we also need to change the direction of the program based on different requirements. Next, let's learn about the if branch statement, which is a flow control statement.

Knowledge Points:

  • if statement
  • if else statement
  • else if statement
  • formatting rules

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Go`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go/BasicsGroup -.-> go/variables("`Variables`") go/FunctionsandControlFlowGroup -.-> go/if_else("`If Else`") go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") subgraph Lab Skills go/variables -.-> lab-149071{{"`If Branch Statement`"}} go/if_else -.-> lab-149071{{"`If Branch Statement`"}} go/functions -.-> lab-149071{{"`If Branch Statement`"}} end

if statement

The most commonly used branch statement is the if statement, which checks if a pre-set condition is true and then decides whether to execute the code block. Here is its format:

if condition {
    code block
}

When the condition is true, the program executes the code block; otherwise, it skips the code block.

Let's take a look at a practical example. Create a new file called if.go and write the following code into it:

package main

import (
    "fmt"
)

func main() {
    var num = 40
    // Get the remainder of dividing two numbers using %
    if num%2 == 0 {
        fmt.Println(num, "is even")
    }
}

The result is as follows:

40 is even

In this program, we first declare an integer variable num. Then, in the if statement, we use the modulo operator % to get the remainder of the division of num by 2, and use the equality operator == to check if the remainder is equal to 0. If it is, the code block is executed and it outputs that the number is even.

if else statement

What should we do if we want to output something else when the condition in the if statement is not met? In this case, we can use the if else statement. If the condition in the if statement is true, it runs the code block in the if statement; otherwise, it runs the code block in the else statement.

The format of the if else statement is similar to the if statement:

if condition {
    code
} else {
    code
}

Let's look at an example. The following program will output whether today is a weekday or a weekend:

package main

import (
    "fmt"
    "time"
)

func main() {
    // Get the current time
    t := time.Now()

    // Check whether it is Saturday or Sunday
    if t.Weekday() == time.Saturday || t.Weekday() == time.Sunday {
        fmt.Println("Today is:", t.Weekday(), "weekend")
    } else {
        fmt.Println("Today is:", t.Weekday(), "weekday")
    }
}

The result is as follows:

Today is: Monday weekday

We use the time package from the standard library to get the current time. Then, by comparing it with Saturday and Sunday, if it is a weekend, the code block in the if statement is executed; otherwise, the code block in the else statement is executed.

else if statement

In addition to checking a single condition, we can also use the else if statement to check multiple conditions.

Its format is as follows:

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

In a branch statement, you can have multiple else if statements, but you can only have one if and one else statement. The position of the else if statement should be between the if and else statements.

Let's rewrite the program in the "if else" section so that it outputs the day of the week:

package main

import (
    "fmt"
    "time"
)

func main() {
    today := time.Now().Weekday()

    if today == time.Monday {
        fmt.Println("Today is Monday")
    } else if today == time.Tuesday {
        fmt.Println("Today is Tuesday")
    } else if today == time.Wednesday {
        fmt.Println("Today is Wednesday")
    } else if today == time.Thursday {
        fmt.Println("Today is Thursday")
    } else if today == time.Friday {
        fmt.Println("Today is Friday")
    } else if today == time.Saturday {
        fmt.Println("Today is Saturday")
    } else {
        fmt.Println("Today is Sunday")
    }
}

After running, the result is as follows:

Today is Monday

In the previous program, we first use time.Now() to get the current time, and then get the day of the week from the current time. In this program, these two lines of code are combined into one line. After getting the day of the week, it matches it with the branch statement to output the day of the week.

Initialization statement in the if statement

In the previous learning, the if statement had only one parameter, the condition:

if condition {
    code
}

The complete parameter also includes an initialization statement, which is an optional parameter in Go. It is usually used for the declaration and initialization of temporary variables, and the initialization statement is separated by a semicolon when used. The syntax is as follows:

if initialization statement; condition {
    code
}

We have rewritten the program in the "if else" section. We moved the variable declaration to the if statement as an initialization statement to shorten the code:

package main

import (
    "fmt"
    "time"
)

func main() {
    if t := time.Now(); t.Weekday() == time.Saturday || t.Weekday() == time.Sunday {
        fmt.Println("Today is:", t.Weekday(), "weekend, studying and recharging")
    } else {
        fmt.Println("Today is:", t.Weekday(), "also studying hard")
    }
}

It can be seen that it runs correctly:

Today is: Monday also studying hard

Note: The scope of the variable declared in the initialization statement is only within the if loop.

Formatting Issues

I don't know if you Go gophers have noticed the formatting requirements of Go when learning if statements.

  • In Go, the keywords if, else, and else if need to be on the same line as the right curly brace }.

  • The else if and else keywords also need to be on the same line as the previous left curly brace, otherwise, the compiler will report an error at runtime.

If we run the program after moving the else statement to the next line, the compiler reports a syntax error.

Summary

In this lab, we have explained the if branch statement, including the following main points:

  • In an if branch code block, there can be multiple else if statements, but there can only be one if and one else statement.
  • The else if statement needs to be placed between the if and else statements.
  • You can use an initialization statement in the if to shorten the code.
  • The compiler enforces that the keywords if, else, and else if must be on the same line as the curly braces.

In the next experiment, we will explain the switch-case multi-condition branch in the branch statement.

Other Go Tutorials you may like