Conditionals (if-else) in Go

·

3 min read

The most basic statement in every programming language is the "if" statement. It is used when we need to do something based on some conditions.

If Statement

package main

import "fmt"

func main() {
    age := 21
    if age > 20 {
        fmt.Println("age is greater than 20")
    }
}

Result: age is greater than 20

Here you can run the code above in the playground: if-statement

We can do something if the initial condition is not satisfied. We should use the if-else statement.

If-Else Statement

package main

import "fmt"

func main() {
    age := 21
    if age == 20 {
        fmt.Println("age is 20")
    } else {
        fmt.Println("age is greater or less than 20")
    }
}

Result: age is greater or less than 20

Here you can run the code above in the playground: if-else-statement

If-Else if Statement

We can have multiple if statements to test two or more conditions.

package main

import "fmt"

func main() {
    age := 21
    if age == 20 {
        fmt.Println("age is 20")
    } else if age < 20 {
        fmt.Println("age is less than 20")
    } else if age > 20 {
        fmt.Println("age is greater than 20")
    } else {
        fmt.Println("code will never got here")
    }
}

Result: age is greater than 20 Here you can run the code above in the playground: if-else if-statement

If initialization

Go has this special way to initialize a variable kind of inside of an "if" statement. In the previous examples, we had to initialize the variable x before using it in the if statement. Let's see how to use it.

package main

import "fmt"

func main() {
    if age := 21; age > 20 {
        fmt.Println("age is 20")
    }
}

Result: age is 20

Here you can run the code above in the playground: if-else if-statement

That's it for conditional statements in Go. At least the if-else-if-else statements.