Control structures


  • if - else
  • switch
  • for

  • No while or do-while loops.

  • No parenthesis around boolean conditions or values.
  • Only equality operator is ==.
  • Other operators: !=, <, >, <=, >=.









if - else

  • Can have multiple conditions.
if message != nil {
} else {
}

// Variable available in special scope, condition is last
if text := "hello"; message != nil {
} else {
}
  • There is no ternary operator in Go—e.g. in Python you can do the following, but not in Go:

Python

# python ternary operator
min = "a is minimum" if a < b else "b is minimum"









switch

  • No break statement needed.
  • fallthrough keyword is used to go to the next case.
switch day {
    case "Wednesday":
        fmt.Println("Time for class! 📚")
    case "Friday":
        fmt.Println("Woooh! Parteeey! 🎉")
    case "Saturday":
        fallthrough
    case "Sunday":
        fmt.Println("Weekend 🌞")
    default:
        fmt.Println("It's another day 😴")
}









switch (with conditions)

  • Great for replacing large if-else chains.
switch {
    case message == nil:
    // ...
    case message != nil && message.Text == "":
    // ...
    case message.Sent == true:
    // ...
    default:
}









for

  • Multi-purpose loop.
// Classic loop
for i := 0; i < len(myCollection); i++ {
}

// Loop over a collection
for index := range myCollection {
}

// Loop over a map
for key, value := range myMap {
}









for (continued)

  • We can emulate a while loop with boolean expressions.
// Emulating a while loop
quit := false
for quit {
    // process ... then set 'quit' to true to exit
}

count := 0
for count < 10 {
    count++
}

// Infinite loop
for {
}









TRY IT OUT

Rob Pike


Build a simple calculator command line application that takes two numbers and an operator as input and outputs the result.

HINT: Use the fmt.Scanf() function to read input from the user.

HINT: Use a switch statement to determine the operation to perform.