In Go, you can use conditional statements, such as if-else
, to control the flow of your program based on certain conditions. Here's how you can use if-else
statements in Go:
if
statement:package main
import "fmt"
func main() {
x := 10
if x > 5 {
fmt.Println("x is greater than 5")
}
}
if-else
statement:package main
import "fmt"
func main() {
x := 3
if x > 5 {
fmt.Println("x is greater than 5")
} else {
fmt.Println("x is smaller than or equal to 5")
}
}
if-else if-else
statement:package main
import "fmt"
func main() {
x := 7
if x > 10 {
fmt.Println("x is greater than 10")
} else if x > 5 {
fmt.Println("x is greater than 5 but less than or equal to 10")
} else {
fmt.Println("x is less than or equal to 5")
}
}
package main
import "fmt"
func main() {
x, y := 5, 10
if sum := x + y; sum > 10 {
fmt.Println("Sum is greater than 10")
} else {
fmt.Println("Sum is less than or equal to 10")
}
}
In this example, sum
is a variable that is only accessible inside the if
statement's block.
Note that the condition given in an if
statement should be a boolean expression (evaluates to either true
or false
). You can use comparison operators (>
, <
, >=
, <=
, ==
, !=
) and logical operators (&&
for AND, ||
for OR, !
for NOT) to form boolean expressions.
Remember to enclose the condition within parentheses. Also, proper indentation is not necessary in Go, but it is a good practice to improve code readability.