Switch and type switch
Go switch statements are powerful but rule-bound; expression switches and type switches solve different problems.
Canonical guidance
- expression switches compare ordinary values
- type switches inspect the dynamic type of an interface value
fallthroughis limited and never applies to type switches
Use when
- choosing between
if,switch, and type assertions - reviewing grouped case logic
- diagnosing case duplication or scope issues
Avoid
- using a type switch on non-interface values
- assuming
fallthroughcarries condition checks forward - mixing unrelated case logic into one giant switch
Preferred pattern
switch v := anyVal.(type) {
case string:
return len(v)
case []byte:
return len(v)
default:
return 0
}
Anti-pattern
- using
fallthroughto fake a multi-condition type switch
Explanation: This is tempting when cases share work, but type switches and expression switches have different rules and fallthrough does not bridge them.
Why
- switch semantics affect control flow, scope, and runtime type handling in one of the most common statement forms