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:

Go

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.

Go

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.

Go

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
Tutorials dojo strip