Course Content
Introduction to GoLang
Introduction to GoLang
Conditional Chaining
We can use the else if
keyword to define an additional condition that will be evaluated in case the previous condition is not met:
index
package main import "fmt" func main() { if (3 > 4) { fmt.Println("3 is greater than 4") } else if (3 > 2) { fmt.Println("3 is greater than 2") } }
In the above program, the expression 3 > 4
is checked first, which is false
; hence the program proceeds to the next statement (3 > 2
) defined using the else if
keyword. The next condition is true
, so the output displays the result of the second Println
statement.
We can add as many additional conditions as needed using else if
statements:
index
package main import "fmt" func main() { if (3 > 4) { fmt.Println("3 is greater than 4") } else if (3 > 3) { fmt.Println("3 is greater than 3") } else if (3 > 2) { fmt.Println("3 is greater than 2") } else if (3 > 1) { fmt.Println("3 is greater than 1") } }
It's important to note that the above program only outputs 3 is greater than 2
, even though the next condition is also true
. This demonstrates that an if-else if
chain stops evaluating conditions as soon as it encounters a true
condition.
This process is referred to as conditional chaining because we are essentially defining conditions in a chain using if
-else if
keywords.
Note
In a conditional chain, only one code block is executed, the one that satisfies the condition, while the rest are skipped.
Alternatively, instead of chaining conditionals using the if
-else if
combination, we can write each condition using separate if
statements. However, this approach produces a different output because it's no longer a single chain; it's a set of separate conditions, and therefore, it won't stop executing if one or more of the conditions are met:
index
package main import "fmt" func main() { if (3 > 4) { fmt.Println("3 is greater than 4") } if (3 > 3) { fmt.Println("3 is greater than 3") } if (3 > 2) { fmt.Println("3 is greater than 2") } if (3 > 1) { fmt.Println("3 is greater than 1") } }
Up to this point, for the sake of simplicity, we have been using values in boolean expressions. However, it is more common to use variables or a combination of variables and values in boolean expressions:
index
package main import "fmt" func main() { var value int = 10 if (value == 10) { fmt.Println("The variable has the expected value.") } }
In a conditional chain, we can use the else
keyword to indicate a code block that should be executed if none of the conditions in the chain are met:
index
package main import "fmt" func main() { var value int = 70 if (value < 50) { fmt.Println("The value is less than 50") } else if (value == 50) { fmt.Println("The value is equal to 50") } else { fmt.Println("The value is greater than 50") } }
Thanks for your feedback!