Go Conditions

Conditional statements in Go are essential for directing the flow of a program. They allow developers to execute specific blocks of code based on given conditions, which evaluate to either true or false.

Tutorials dojo strip



Comparison Operators in Go

Go includes several comparison operators, familiar from mathematical contexts:

  • Less than <
  • Less than or equal to <=
  • Greater than >
  • Greater than or equal to >=
  • Equal to ==
  • Not equal to !=

These operators help evaluate relationships between values and can be combined for more complex conditions.




Logical Operators in Go

Go also supports logical operators for creating more advanced conditions:

  • Logical AND && – Returns true if both operands are true.
  • Logical OR || – Returns true if at least one operand is true.
  • Logical NOT ! – Negates the value of a condition, converting true to false and vice versa.

These operators can be used individually or together for decision-making scenarios.




Examples of Conditions

ducati > yamaha   // Ducati's speed is greater than Yamaha's
honda != suzuki   // Honda's performance is not equal to Suzuki's
(ducati > yamaha) && (yamaha > honda)   // Ducati is faster than Yamaha AND Yamaha is faster than Honda
(honda == yamaha) || suzuki            // Honda equals Yamaha, OR Suzuki is the choice




Types of Conditional Statements in Go

Go provides the following constructs for conditional logic:

if Statement

This is used when you want to run a block of code only if a specific condition is true.

if ducati > yamaha {
    fmt.Println("Ducati is faster than Yamaha!")
}

else Statement

An else block runs when the condition in the if statement evaluates to false.

if ducati < yamaha {
    fmt.Println("Yamaha wins!")
} else {
    fmt.Println("Ducati stays ahead!")
}

else if Statement

Use else if to add another condition to check if the original if condition is false.

if ducati > yamaha {
    fmt.Println("Ducati dominates the race!")
} else if yamaha > honda {
    fmt.Println("Yamaha outperforms Honda!")
} else {
    fmt.Println("A close match between the brands.")
}

switch Statement

The switch statement is ideal for testing multiple conditions and providing alternatives in a clear format.

switch ducati {
case yamaha:
    fmt.Println("Ducati and Yamaha are evenly matched.")
case honda:
    fmt.Println("Ducati and Honda have comparable features.")
default:
    fmt.Println("Ducati stands unique among the brands.")
}
Tutorials dojo strip
Scroll to Top