Fundamentals 11 min read

Why Use a Switch Without an Expression in Go? Exploring the ‘switch true’ Pattern

This article explains the unconventional Go switch without an expression, shows how it works like ‘switch true’, compares it with equivalent if‑else logic, examines the generated assembly, and discusses when this compact pattern is useful for prefix‑based checks.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Why Use a Switch Without an Expression in Go? Exploring the ‘switch true’ Pattern

While browsing Go source code I discovered an interesting use of switch without an expression and decided to share it.

Note that this is not a typed switch (where the case values are types).

Original 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
    }
}

The function runs systemctl to get the service status, then uses strings.HasPrefix on the output to decide which status to return.

Why the switch works

If a 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 (here true), that branch is taken and the remaining cases are skipped (unless fallthrough is used).

Thus the above code is essentially the same as a series of if statements checking each prefix in order.

Equivalent if version

if strings.HasPrefix(out, "active") {
    return StatusRunning, nil
}
if strings.HasPrefix(out, "inactive") {
    // same logic as the corresponding case above
    ...
}
if strings.HasPrefix(out, "activating") {
    return StatusRunning, nil
}
if strings.HasPrefix(out, "failed") {
    return StatusUnknown, errors.New("service in failed state")
}
return StatusUnknown, ErrNotInstalled

Both versions compile to very similar assembly; the switch version merely groups the prefix checks into a single switch construct.

The generated assembly for the switch version shows a sequence of CALL strings.HasPrefix checks followed by jumps to the appropriate return blocks, which mirrors the control flow of the if version.

Performance considerations

Because the generated code is almost identical, there is no measurable performance advantage. The extra jump in the switch version may even improve instruction‑cache locality for some patterns, but in practice the difference is negligible.

When to use this pattern

If you need to test a value against multiple boolean conditions (e.g., several string prefixes) and want a compact, readable representation, a switch without an expression can be clearer than a chain of if statements. For simple or single‑condition logic, stick with if.

Understanding this pattern helps you read existing Go code that uses it, preventing confusion when you encounter it in the wild.

Link: https://www.cnblogs.com/apocelipes/p/17368617.html

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceCode GenerationGoControl Flowswitch
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.