Control Statements
Let's explore control statements in golang
1. If/else statements
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.")
}
}2. Switch statements
Last updated