Conditions
If-else Statement
Executes a block of code when a condition is true.
if condition {
// code runs if condition is true
} else if anotherCondition {
// code runs if it gets here and anotherCondition is true
} else {
// code runs if none of the above are true
}-
Go lets you declare a variable that only exists in the
ifandelseblocks:s := "Hello" if n := len(s); n == 1 { fmt.Println("n is:", n) } else if n >= 2 { fmt.Println("n is:", n) } else { fmt.Println("Empty string", n) } // n is: 5 fmt.Println("n is:", n) // <-- compiler: undefined: n
Switch Statement
Executes the block for the matching case.
switch expression {
case value1:
// code runs if expression == value1
case value2:
// code runs if expression == value2
case value3, value4:
// code runs if expression == value3 or value4
default:
// code runs if expression does not match any case
}Go auto
breakafter each case implicitly, but the keyword can still be used.
-
Using the
fallthroughkeyword overrides the implicitbreakbehavior and continues execution into the next case:a := 2 switch a { case 1: fmt.Println("One") case 2: fmt.Println("Two") fallthrough case 3: fmt.Println("Three") case 4: fmt.Println("Four") default: fmt.Println("None of above") } // Two // Three -
You can also declare a variable for case matching that only exists within the
switchblock:s := "hi" switch n := len(s); n { case 1: fmt.Println("n is:", n) case 2: fmt.Println("n is:", n) default: fmt.Println("None of above", n) } // n is: 2 fmt.Println("n is:", n) // <-- compiler: undefined: n -
Omitting the expression makes the
switchstatement act like anif-elsestatement:a := 3 switch { case a == 1: fmt.Println("One") case a == 2: fmt.Println("Two") case a == 3 || a == 4: fmt.Println("Three or Four") default: fmt.Println("None of above") } // Three or Four