Constant Patterns Versus Bindings

Match against named constants with path patterns, and see why a lowercase identifier in the same position silently becomes an always-matching binding.

RustData Integrity

Code

rustsnippet
23 lines
const STATUS_NOT_FOUND: u32 = 404;

fn label(code: u32) -> &'static str {
    // constant patterns: 大写常量名构成路径模式,按值比较
    match code {
        STATUS_NOT_FOUND => "not found",
        _ => "other",
    }
}

fn buggy(code: u32) -> String {
    match code {
        // lowercase identifier 不是常量模式:status_not_found 绑定任意输入
        status_not_found => format!("binding swallowed {}", status_not_found),
    }
}

fn main() {
    println!("label(404): {}", label(404));
    println!("label(500): {}", label(500));
    println!("buggy(200): {}", buggy(200));
    println!("buggy(404): {}", buggy(404));
}

How it works

The working surface is the functions label, buggy and main — everything else is wiring.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Caveats

  • Self-contained — no imports beyond what the runtime already provides.

Using it

The primary signature is fn label(code: u32) -> &'static str

Running the file prints labeled results such as label(404):, label(500):, buggy(200): — each operation’s effect is visible in the output.

Running the file executes main, which drives label and buggy in order.

Key statements

fn label(code: u32) -> &'static str {
// constant patterns: 大写常量名构成路径模式,按值比较
match code {
STATUS_NOT_FOUND => "not found",
_ => "other",
}
}
fn buggy(code: u32) -> String {
match code {
// lowercase identifier 不是常量模式:status_not_found 绑定任意输入
status_not_found => format!("binding swallowed {}", status_not_found),
}
}

Interactive Tools for This Topic

FAQ

What does Constant Patterns Versus Bindings print when run?
Invoke the file as-is — the `label(404):`, `label(500):`, `buggy(200):` prefixes identify which step printed each line.