We've already covered an example or two using if statements, but let's dig into the syntax required by ifs and switches. In today's post we're going to cover 6 more reserved words: if
, else
, switch
, case
, fallthrough
, and default
.
If
If statements are pretty standard in Go (similar to C and its derivatives). As always, it is important to remember "the one true brace style."
const amSam = false
name := "Samuel"
// good
if (amSam) {
fmt.Println("I am Sam")
} else if name == "Samuel" {
fmt.Println("I am Samuel")
} else {
fmt.Println("I am not Sam")
}
// gives an error
if amSam
{
fmt.Println("I am Sam")
}
// gives an error
else {
fmt.Println("I am not Sam")
}
It is also important to note that if we want to include an else
or an else if
we must do so on the same line as the previous conditional's closing curly brace. Also, we can put parentheses around the condition if we want.
Switch
Ahh switch statements. I can never remember their syntax, so I'm glad I'm writing it here for at least one language!
favCharacter := "Catbug"
switch favCharacter {
case "Jelly Kid":
fmt.Println("We can be friends.")
case "Catbug":
fmt.Println("Instant best friend.")
default:
fmt.Println("Really?")
}
By default, if a case evaluates to true, control leaves the switch block. This means if we have multiple case statements that could be true only the first executes. If we do not want this behavior, we can use the fallthrough
keyword:
num := 5
switch {
case num < 10 :
fmt.Printf("%v is less than 10\n", num)
fallthrough
case num < 15:
fmt.Printf("%v is less than 15\n", num)
fallthrough
case num > 20:
fmt.Printf("%v is greater than 20\n", num)
}
// every case is executed
IMPORTANT: It is only recommended to use fallthrough
if the behavior is clearly understood. As we can see in the example, even though 5 is not greater than 20, the preceding case contains the fallthrough
keyword, thus, 5 is greater than 20
will be printed.
Also, notice in the last example how we don't have to include a variable after switch
? This is called an expressionless switch statement. We are just checking some conditions in each case. They don't have to (but probably should be) related.
We can have multiple conditions in a single case, but it is important to note that duplicate cases are not allowed.
// good
color = "yellow"
switch color {
case "red", "yellow", "blue":
fmt.Println("A primary color")
case "orange", "green", "purple":
fmt.Println("A secondary color")
default:
fmt.Println("A new color?")
}
// error: duplicate case
switch color {
case "yellow":
fmt.Println("A primary color")
case "yellow":
fmt.Println("The best primary color")
}
Conclusion
Always remember the "one true brace style" and avoid using fallthroughs if you can!
Top comments (0)