0
0
Goprogramming~5 mins

If–else statement in Go

Choose your learning style9 modes available
Introduction

An if-else statement helps your program make choices. It runs different code depending on a condition.

To check if a user is old enough to access a website.
To decide if a number is positive or negative.
To choose what message to show based on the time of day.
To handle errors by checking if something went wrong.
To run different code when a button is clicked or not.
Syntax
Go
if condition {
    // code to run if condition is true
} else {
    // code to run if condition is false
}

The condition must be a statement that results in true or false.

Curly braces { } are required even for one line of code inside if or else.

Examples
This checks if age is 18 or more, then prints a message accordingly.
Go
if age >= 18 {
    fmt.Println("You are an adult.")
} else {
    fmt.Println("You are a minor.")
}
Prints "Passed" if score is above 50, otherwise "Failed".
Go
if score > 50 {
    fmt.Println("Passed")
} else {
    fmt.Println("Failed")
}
Sample Program

This program checks the temperature and prints if it is hot or cool.

Go
package main

import "fmt"

func main() {
    temperature := 30
    if temperature > 25 {
        fmt.Println("It's hot outside.")
    } else {
        fmt.Println("It's cool outside.")
    }
}
OutputSuccess
Important Notes

You can add more conditions using else if for multiple choices.

Always use curly braces to avoid mistakes, even if the block has one line.

Summary

If-else lets your program choose between two paths.

Use it when you want to run code only if a condition is true or false.

Remember to write conditions that result in true or false.