0% found this document useful (0 votes)
22 views1 page

Go by Example - If - Else

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views1 page

Go by Example - If - Else

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Go by Example: If/Else https://gobyexample.

com/if-else

Go by Example: If/Else
Branching with if and else in Go is straight-
forward.

package main

import "fmt"

func main() {

Here’s a basic example. if 7%2 == 0 {


fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}

You can have an if statement without an else. if 8%4 == 0 {


fmt.Println("8 is divisible by 4")
}

Logical operators like && and || are often useful in if 8%2 == 0 || 7%2 == 0 {
conditions. fmt.Println("either 8 or 7 are even")
}

A statement can precede conditionals; any if num := 9; num < 0 {


variables declared in this statement are available fmt.Println(num, "is negative")
in the current and all subsequent branches. } else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}

Note that you don’t need parentheses around


conditions in Go, but that the braces are required.

$ go run if-else.go
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

There is no ternary if in Go, so you’ll need to use a


full if statement even for basic conditions.

Next example: Switch.

by Mark McGranaghan and Eli Bendersky | source | license

1 of 1 11/26/24, 23:27

You might also like