0
0
Goprogramming~5 mins

If statement in Go

Choose your learning style9 modes available
Introduction

An if statement helps your program make choices by running code only when certain conditions are true.

To check if a user entered the correct password before allowing access.
To decide if a number is positive or negative and print a message.
To run a special offer only if a customer buys more than 5 items.
To check if a file exists before trying to open it.
Syntax
Go
if condition {
    // code to run if condition is true
}

The condition must be a boolean expression (true or false).

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

Examples
This runs the print only if x is bigger than 10.
Go
if x > 10 {
    fmt.Println("x is greater than 10")
}
This checks if the name is exactly "Alice" and greets her.
Go
if name == "Alice" {
    fmt.Println("Hello, Alice!")
}
This runs if the boolean variable isRaining is true.
Go
if isRaining {
    fmt.Println("Take an umbrella.")
}
Sample Program

This program checks if the age is 18 or more and prints a message if true.

Go
package main

import "fmt"

func main() {
    age := 20
    if age >= 18 {
        fmt.Println("You are an adult.")
    }
}
OutputSuccess
Important Notes

You can add else or else if to handle other cases, but if alone is enough for simple checks.

Make sure the condition inside if returns true or false, not other types.

Summary

If statements let your program choose what to do based on conditions.

Use curly braces { } to group the code that runs when the condition is true.

Conditions must be boolean expressions that say true or false.