Conditional statements are fundamental in programming languages for controlling the flow of execution based on specific conditions. In Go, the primary conditional statements are if
, else if
, else
, and switch
. These statements enable developers to direct the program's execution path according to the results of logical expressions.
The if
statement in Go is used to execute a block of code if a specified condition evaluates to true
.
In this example, the condition x > 5
evaluates to true
, so the code inside the if
block is executed, and the output is:
The if-else
statement allows you to execute one block of code if the condition is true
and another block if the condition is false
.
Here, the condition x > 5
is false
, so the else
block is executed, producing:
The if-else if-else
statement chain allows you to test multiple conditions in sequence. The first condition that evaluates to true
will execute its corresponding block of code.
Since x
is 7, the first condition is false
, but the second condition is true
, so the output is:
The switch
statement in Go is used to simplify complex if-else if
chains by allowing a variable or expression to be tested against multiple cases. It's particularly useful for checking a variable against multiple possible values.
Since day
is "Tuesday"
, the output is:
In Go, you can use a switch
statement without an expression. This acts as a cleaner alternative to if-else
chains and evaluates each case
as a boolean expression.
Here, the switch
evaluates the first case that is true
, producing:
This basic example checks if the username
and password
match the expected values and prints the appropriate message.
The switch statement evaluates the grade
and prints the corresponding message.
Conditional statements in Go, including if
, else
, else if
, and switch
, provide powerful tools for controlling the flow of execution in your programs. These constructs allow you to handle different conditions effectively, making your code more flexible and easier to manage.