Control Statements
Let's explore control statements in golang
Last updated
Let's explore control statements in golang
Last updated
Golang only provides two control statements, if/else and switch cases
Here is a basic if/else branching statement
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Println("Enter your name: ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
name := scanner.Text()
if strings.ToLower(name) == "jack sparrow" {
fmt.Println("Not all treasure's silver and gold, mate.")
} else {
fmt.Println("You're not a pirate")
}
fmt.Println("\nEnter a number to decide your fate: ")
scanner.Scan()
num, _ := strconv.Atoi(scanner.Text())
// parentheses are not required around the conditional
// but curly braces are always required
if num < 0 {
fmt.Println(num, "is negative")
} else if num%2 == 0 {
fmt.Println(num, "is a lucky number. You get candy.")
} else {
fmt.Println(num, "is an unlucky number. You get no candy.")
}
}
// sample output
$ go run control_statements.go
Enter your name:
jack sparrow
Not all treasure's silver and gold, mate.
Enter a number to decide your fate:
2
2 is a lucky number. You get candy.
Switch statements allow us to do pattern matching, and express conditions around multiple branches. Here is how they work with an example:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("What is the magic number?")
var num int
fmt.Fscan(os.Stdin, &num)
switch {
case num < 5:
fmt.Println("Your number is too low")
case num == 5:
fmt.Println("Nice! You found the magic number!")
case num > 5:
fmt.Println("Your number is too high")
// the default case allows us to catch all other patterns
default:
fmt.Println(num, "is that even a number?")
}
}
Switch cases can also have multiple conditions in one case. For example,
switch {
case num > 5, num < 10:
fmt.Println("number is between 5 and 10")
default:
fmt.Println("number not in range at all")
}
Switch statements with a condition are synonymous to if/else statements as in the example above. In the next section, we will look at Loops in go and how they work.