Conditional statements in Go, such as if and else, allow you to execute different blocks of code based on certain conditions.
As in other languages, this helps in controlling the flow of your program.
See the below for an example of using if and else in Go.
package main
import "fmt";
func main() {
x := 10
y := 20
if x < y {
fmt.Println("x is less than y")
} else if x > y {
fmt.Println("x is greater than y")
} else {
fmt.Println("x is equal to y")
}
// Short statement with if
if z := x + y; z > 20 {
fmt.Println("z is greater than 20")
} else {
fmt.Println("z is not greater than 20")
}
}
Step-by-Step:
Basic If Statement:
if x < y checks if x is less than y and executes the corresponding block.
Else If Statement:
else if x > y checks if x is greater than y and executes the corresponding block if true.
Else Statement:
else executes if none of the previous conditions are met.
Short Statement with If:
if z := x + y; z > 20 declares and initializes z within the if statement and checks if z is greater than 20.
If and else statements are used to execute different blocks of code based on certain conditions.
In Go, you can also use a short statement with if to declare and initialize variables within the if statement.
Otherwise, the syntax for if and else in Go is similar to other languages.