Conditions
If-else Statement
Executes a block when a condition evaluates to true.
if condition {
// runs if condition is true
} else if anotherCondition {
// runs if it gets here and this condition is true
} else {
// runs if none of the above are true
}-
Variable declaration is allowed inside the
ifstatement, with scope limited to theif-elseblock: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 first matching case.
switch expression {
case value1:
// runs if expression == value1
case value2:
// runs if expression == value2
case value3, value4:
// runs if expression == value3 or value4
default:
// runs if no case matches
}Each case ends with an implicit
break(the keyword itself can still be used).
-
fallthroughoverrides the implicitbreakand continues 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 -
Variable declaration is allowed inside the
switchstatement, with scope limited to theswitchblock: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
switchbehave like anif-elsechain.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