switch_statement 1.0.0

A simple switch statement macro
Documentation
  • Coverage
  • 50%
    1 out of 2 items documented1 out of 1 items with examples
  • Size
  • Source code size: 4.82 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 480.52 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • camsteffen/switch-statement-rust
    7 1 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • camsteffen

Switch Statement For Rust

A simple macro to emulate a switch statement in Rust.

crates.io Docs License

Description

The switch! macro looks similar to match. But instead of pattern matching, each left-hand-side expression is interpreted as an expression instead of a pattern. One use case for this is to match against constants joined with bitwise OR. The output of the macro is a match with if guards.

Example

const A: u32 = 1 << 0;
const B: u32 = 1 << 1;
const C: u32 = 1 << 2;

fn flag_string(input: u32) -> &'static str {
    switch! { input;
        A => "A",
        // bitwise OR
        A | B => "A and B",
        A | B | C => "A and B and C",
        B | C => "B and C",
        _ => "other"
    }
}

The above code expands to:

const A: u32 = 1 << 0;
const B: u32 = 1 << 1;
const C: u32 = 1 << 2;

fn flag_string(input: u32) -> &'static str {
    match input {
        v if v == A => "A",
        v if v == A | B => "A and B",
        v if v == A | B | C => "A and B and C",
        v if v == B | C => "B and C",
        _ => "other"
    }
}