Basics

Go If Else

Conditional Statements

Go if-else statements control flow with simple syntax.

Introduction to If Else in Go

In Go, if-else statements are used to control the flow of execution based on conditions. They allow you to execute specific blocks of code if a condition evaluates to true, and optionally execute another block if the condition is false. This is fundamental for decision-making in programming.

Syntax of If Else Statements

The basic syntax of an if-else statement in Go is straightforward. It involves an if keyword followed by a condition in parentheses, a block of code to execute if the condition is true, and an optional else block for false conditions.

Using If Else with Examples

Let's look at a simple example where we determine if a number is even or odd.

In this example, the condition num%2 == 0 checks if the number is evenly divisible by 2. If it is, the program prints "Even"; otherwise, it prints "Odd".

Nested If Else Statements

Go also supports nested if-else statements, which means you can include an if-else block inside another if or else block. This is useful for checking multiple conditions.

In this example, the program checks if a person is a minor, adult, or senior based on their age. The nested if-else structure allows for multiple conditions to be evaluated sequentially.

If Else without Parentheses

Unlike some other languages, Go does not require parentheses around the condition in an if statement. This makes the syntax cleaner and easier to read.

Previous
Operators