Conditional Statements
20.01.2025 · dayanch
Conditional statements are essential for controlling the flow of a program based on certain conditions. In Go, you can use
if, else if, and switchIf Statement
The simplest form of a conditional statement is the
ifExample 1: Basic If Statement
x := 10 if x > 5 { fmt.Println("x is greater than 5") }
This will print:
x is greater than 5
Else If Statement
You can chain multiple conditions using
else ifExample 2: Else If Statement
x := 3 if x > 5 { fmt.Println("x is greater than 5") } else if x > 2 { fmt.Println("x is greater than 2 but less than or equal to 5") }
This will print:
x is greater than 2 but less than or equal to 5
Else Statement
The
elseExample 3: Else Statement
x := 1 if x > 5 { fmt.Println("x is greater than 5") } else { fmt.Println("x is less than or equal to 5") }
This will print:
x is less than or equal to 5
Switch Statement
The
switchExample 4: Switch Statement
year := "2024" switch year { case "2023": fmt.Println("Year is 2023") default: fmt.Println("Year is not recognized") }
This will print:
year is not recognized
Conclusion
Conditional statements are fundamental in programming, allowing you to control the flow of your program based on specific conditions. In Go, you can use
ifelse ifswitch