In this example, we will show you how to use the If/Else condition in Go with an example.
Similar to other programming languages, branching with If/Else in Go is straightforward.
Go - If/Else Example
The below example demonstrates the usage of the If/Else condition in the Go language:
package main
import "fmt"
func main() {
// if/else condition
if 9%2 == 0 {
fmt.Println("9 is even")
} else {
fmt.Println("9 is odd")
}
// Using if statement without an else.
if 12%4 == 0 {
fmt.Println("12 is divisible by 4")
}
// A statement can precede conditionals;
// any variables declared in this statement are available in all branches.
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
Output:
9 is odd 12 is divisible by 4 9 has 1 digit
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course