Control Statements

Let's explore control statements in golang

Golang only provides two control statements, if/else and switch cases

1. If/else statements

Here is a basic if/else branching statement

control_statements.go
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.")
  }
}

golang does not have ternary if/else statements. However, if blocks can be used without an else statement. For example

Variables can also be initialized in the if statement, as is the example above. The variable will be available for the current branch and the subsequent branches

2. Switch statements

Switch statements allow us to do pattern matching, and express conditions around multiple branches. Here is how they work with an example:

Switch cases can also have multiple conditions in one case. For example,

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.

Last updated