Simple usage examples of go language if and else statements

  • 2020-06-01 10:00:12
  • OfStack

This article illustrates the use of go language if/else statements. I will share it with you for your reference as follows:

The if else branch is straightforward in the go language.

Here's a simple example.

if statements can be used without else.

You can add additional statements before conditional statements. The scope of the variables declared in this statement is in all branches.

Note: conditional statements do not need parentheses in go. But you have to have curly braces in your branches.
There are no 3-yuan conditional statements in go, so even for simple conditional statements you must use the entire if statement (that is, there is no ? in go; Expression:
).

Sample code:

package main
import "fmt"
func main() {
    if 7%2 == 0 {
        fmt.Println("7 is even")
    } else {
        fmt.Println("7 is odd")
    }
    if 8%4 == 0 {
        fmt.Println("8 is divisible by 4")
    }
    if num := 9; num < 0 {
        fmt.Println(num, "is negative")
    } else if num < 10 {
        fmt.Println(num, "has 1 digit")
    } else {
        fmt.Println(num, "has multiple digits")
    }
}

Run the test as follows:

$ go run if-else.go 
7 is odd
8 is divisible by 4
9 has 1 digit

I hope this article has been helpful to you in programming Go.


Related articles: