Go if Statement

The if statement is a fundamental part of Go programming that allows you to execute specific blocks of code based on whether a condition evaluates to true. This is particularly useful for decision-making processes within your programs.

Tutorials dojo strip



Syntax

The syntax for an if statement in Go is:

if condition {
    // Code to execute if the condition is true
}

Important Note: The keyword if must always be in lowercase. Writing it as If or IF will result in an error.




Example 1: Simple Comparison

Let’s check if one number is greater than another. If the condition is true, a message will be printed to the console.

package main
import ("fmt")

func main() {
    if 50 > 30 {
        fmt.Println("50 is greater than 30")
    }
}




Example 2: Testing with Variables

You can also use variables to test conditions. Below is an example using motorcycle brands to make it more engaging.

package main
import ("fmt")

func main() {
    ducati := 50
    yamaha := 30

    if ducati > yamaha {
        fmt.Println("Ducati is faster than Yamaha")
    }
}

Explanation of Example 2

In this example, we declare two variables, ducati and yamaha, representing arbitrary values (e.g., speeds or ratings). The condition ducati > yamaha evaluates whether Ducati’s value is greater than Yamaha’s. Since 50 is greater than 30, the program prints “Ducati is faster than Yamaha” to the console.

Tutorials dojo strip
Scroll to Top