If Branch Statement in Golang

GolangGolangBeginner
Practice Now

Introduction

When creating a to-do plan, if a task 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(("`Golang`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go(("`Golang`")) -.-> go/AdvancedTopicsGroup(["`Advanced Topics`"]) go/BasicsGroup -.-> go/values("`Values`") go/BasicsGroup -.-> go/variables("`Variables`") go/FunctionsandControlFlowGroup -.-> go/if_else("`If Else`") go/FunctionsandControlFlowGroup -.-> go/switch("`Switch`") go/AdvancedTopicsGroup -.-> go/time("`Time`") subgraph Lab Skills go/values -.-> lab-149071{{"`If Branch Statement in Golang`"}} go/variables -.-> lab-149071{{"`If Branch Statement in Golang`"}} go/if_else -.-> lab-149071{{"`If Branch Statement in Golang`"}} go/switch -.-> lab-149071{{"`If Branch Statement in Golang`"}} go/time -.-> lab-149071{{"`If Branch Statement in Golang`"}} end

if statement

The most commonly used branching 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:

cd ~/project
touch if.go
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")
    }
}

Run the program:

go run if.go

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:

cd ~/project
touch if_else.go
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")
    }
}

Run the program:

go run if_else.go

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 condition {
    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 else if statement should be positioned between the if and else statements.

Let's rewrite the program in the "if else" section to output the day of the week:

Update the if_else.go file:

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")
    }
}

Run the program:

go run if_else.go

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 typically 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")
    }
}

Run the program:

go run if_else.go

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 block.

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 a syntax error at compile time.

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 must 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.

Other Golang Tutorials you may like