Unlocking Go’s Switch‑True Trick: Efficient Service Status Checks Explained
This article explores an unconventional Go switch‑true pattern used for checking systemd service status, compares it with equivalent if‑else logic, examines the generated assembly, and discusses when this style is advantageous for handling multiple string‑prefix conditions.
While browsing source code I discovered an interesting use of the switch statement in Go and decided to share it.
Note that this discussion is not about typed switches where the case statements are types.
Here is the original code (simplified):
<code>func (s *systemd) Status() (Status, error) {
exitCode, out, err := s.runWithOutput("systemctl", "is-active", s.unitName())
if exitCode == 0 && err != nil {
return StatusUnknown, err
}
switch {
case strings.HasPrefix(out, "active"):
return StatusRunning, nil
case strings.HasPrefix(out, "inactive"):
// inactive can also mean it’s not installed, check unit files
exitCode, out, err = s.runWithOutput("systemctl", "list-unit-files", "-t", "service", s.unitName())
if exitCode == 0 && err != nil {
return StatusUnknown, err
}
if strings.Contains(out, s.Name) {
// unit file exists, installed but not running
return StatusStopped, nil
}
// no unit file
return StatusUnknown, ErrNotInstalled
case strings.HasPrefix(out, "activating"):
return StatusRunning, nil
case strings.HasPrefix(out, "failed"):
return StatusUnknown, errors.New("service in failed state")
default:
return StatusUnknown, ErrNotInstalled
}
}
</code>In short, the function runs
systemctlto obtain the service status, then uses
strings.HasPrefixchecks inside a switch without an expression to decide which status to return.
The key points about this switch form are:
If the switch has no expression it is equivalent to
switch true.
Case expressions are evaluated from top to bottom, left to right.
When a case expression evaluates to the same value as the switch expression (true), that branch is taken and the remaining cases are ignored (unless
fallthroughis used).
Thus the original code works like a series of
if … else if …checks, but the author prefers the switch syntax because it groups related conditions together and can be more readable when many prefixes are tested.
A simplified version of the pattern looks like this:
<code>switch {
case strings.HasPrefix(cmdOutput, "active"):
return 1
case strings.HasPrefix(cmdOutput, "inactive"):
if flag > 0 {
return 2
}
return -1
case strings.HasPrefix(cmdOutput, "activating"):
return 1
case strings.HasPrefix(cmdOutput, "failed"):
return -1
default:
return -2
}
</code>Both the switch‑based and the equivalent
ifimplementation compile to almost identical assembly, so there is no performance advantage. The author inspected the generated assembly with Compiler Explorer to confirm this.
The pattern is useful when you have several mutually exclusive string prefixes (or other boolean predicates) that cannot be expressed as constant values. Using a switch groups the predicates and makes the intent clearer, especially when the number of cases grows.
If your logic does not fit this scenario, a plain
if … elsechain is simpler and more familiar.
Understanding this uncommon switch style helps you read existing Go code that uses it, even if you rarely write it yourself.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.