The if
statement in Go is used to execute a block of code if a condition is met. The if
statement can also be combined with an else
statement to execute a different block of code if the condition is not met.
Here’s an example of an if
statement in Go:
package main
import "fmt"
func main() {
x := 10
if x > 5 {
fmt.Println("x is greater than 5")
}
}
In this example, the condition x > 5
is evaluated and if it is true, the message "x is greater than 5"
is printed.
Here’s an example of an if
statement combined with an else
statement in Go:
package main
import "fmt"
func main() {
x := 5
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is not greater than 10")
}
}
In this example, the condition x > 10
is evaluated and if it is true, the message "x is greater than 10"
is printed. If the condition is not met, the message "x is not greater than 10"
is printed.
It is also possible to chain multiple if
statements together using else if
:
package main
import "fmt"
func main() {
x := 15
if x > 20 {
fmt.Println("x is greater than 20")
} else if x > 10 {
fmt.Println("x is greater than 10 but not greater than 20")
} else {
fmt.Println("x is not greater than 10")
}
}
In this example, the first condition x > 20
is evaluated. If it is true, the message "x is greater than 20"
is printed. If it is not true, the next condition x > 10
is evaluated, and if it is true, the message "x is greater than 10 but not greater than 20"
is printed. If both conditions are not met, the message "x is not greater than 10"
is printed.
In this tutorial, we’ve covered the if
statement in Go and how to use it with an else
statement. The if
statement is a powerful tool for controlling the flow of execution in a Go program.
Leave a Reply