Conditional Statements
If else Statements
- These are the decision-making statements just like in any other programming language.
- The IF statement is a decision-making statement that directs a program's decision depending on a set of rules.
- First, the if condition checks if it passes, then the code in the if blocks runs otherwise the code in the else block runs.
Example to define an if-else Statement
package main
import "fmt"
func main() {
heistReady := false
if heistReady {
fmt.Println("Let's go!)
} else {
fmt.Println("Act normal")
}
}
//Prints Act normal
else if Statements
- else if statements are used to check for multiple conditions.
- Else and else if statements cannot run without if statement.
func main() {
amountStolen := 64650
if amountStolen > 1000000 {
fmt.Println("We've hit the jackpot!")
} else if amountStolen >= 5000 {
fmt.Println("Think of all the candy we can buy!")
} else {
fmt.Println("Why did we even do this?")
}
Comparison Operator
- So far, we've only checked on boolean values. We can, however, use comparison operators to examine more than one value. Here are two often-used comparison operators.
== (Is equal to)
!= (Is not equal to)
< (Less than)
> (Greater than)
<= (Less than or equal to)
>= (Greater than or equal to)
func main() {
lockCombo := "2-35-19"
robAttempt := "2-35-19"
if lockCombo == robAttempt {
fmt.Println("The vault is now opened.") //prints this line
}
}
Logical Operator
- This helps us to check multiple conditions at the same time regardless of comparison operator which only one condition at a time.
&& And operation
|| Or operation
! Not
func main() {
rightTime := true
rightPlace := true
if rightTime && rightPlace {
fmt.Println("We're outta here!") //prints This line
} else {
fmt.Println("Be patient...")
}
enoughRobbers := false
enoughBags := true
if enoughRobbers || enoughBags {
fmt.Println("Grab everything") //prints this line
} else {
fmt.Println("Grab whatever you can!")
}
Switch Statement
- A switch statement is a form of control mechanism that allows the value of a variable to change the control flow of programme.
- In else if statements we have to write so many else if conditions to check a particular condition.
- To overcome the problem of rewriting so many else if conditions, switch statements were introduced to check so many conditions.
func main() {
clothingChoice := "sweater"
switch clothingChoice {
case "shirt":
fmt.Println("We have shirts in S and M only.")
case "polos":
fmt.Println("We have polos in M, L and Xl")
case "sweater":
fmt.Println("We have sweaters in S, M, L and XL") //prints this line
default:
fmt.Println("Sorry, we don't carry that")
}
Short Declaration statements
- Go also provides a way to declare short variables inside a conditional statement before we provide any condition.
Syntax is as follows
x := 8
y := 9
if product := x * y; product > 60 {
fmt.Println(product, " is greater than 60") //prints 72 is greater than 60
}