Skip to content

Instantly share code, notes, and snippets.

@brendanzab
Created October 12, 2012 06:56
Show Gist options
  • Save brendanzab/3877690 to your computer and use it in GitHub Desktop.
Save brendanzab/3877690 to your computer and use it in GitHub Desktop.
cond! and switch! macros for Rust

Scheme-style cond

macro_rules! cond(
    ($($pred:expr => $body:block),+ _ => $default:block) => (
        $(if $pred $body else)+
        
        $default
    )
)

fn main() {
    let x = 102;
    cond!(
        x < 100 => { io::println(~"woops"); },
        x > 300 => { io::println(~"hullo"); }
        _       => { io::println(~"bananas"); }
    )
}

C-style switch

Rust's match statement can't handle the use of variables and constants from parent scopes because it conflicts with pattern matching. The alternative is to use lots of ifs and elses:

fn key_to_str(key: int) -> ~str {
    // If we tried using 'match' here we'd get an error for each sub-statement:
    // `error: pattern variable conflicts with a constant in scope`
    if      key == GLFW_KEY_0 { ~"0" }
    else if key == GLFW_KEY_1 { ~"1" }
    else if key == GLFW_KEY_2 { ~"2" }
    else if key == GLFW_KEY_3 { ~"3" }
    else if key == GLFW_KEY_4 { ~"4" }
    else if key == GLFW_KEY_5 { ~"5" }
    else if key == GLFW_KEY_6 { ~"6" }
    else if key == GLFW_KEY_7 { ~"7" }
    else if key == GLFW_KEY_8 { ~"8" }
    else if key == GLFW_KEY_9 { ~"9" }
    else { fail(~"Unsupported key."); }
}

Here's a switch macro to help:

macro_rules! switch(
    ($var:expr { $($pred:expr => $body:block),+ _ => $default:block }) => (
        $(if $var == $pred $body else)+
        
        $default
    )
)

fn key_to_str(key: int) -> ~str {
    switch!(key {
        GLFW_KEY_0  => { ~"0" },
        GLFW_KEY_1  => { ~"1" },
        GLFW_KEY_2  => { ~"2" },
        GLFW_KEY_3  => { ~"3" },
        GLFW_KEY_4  => { ~"4" },
        GLFW_KEY_5  => { ~"5" },
        GLFW_KEY_6  => { ~"6" },
        GLFW_KEY_7  => { ~"7" },
        GLFW_KEY_8  => { ~"8" },
        GLFW_KEY_9  => { ~"9" }
        _           => { fail(~"Unsupported key."); }
    })
}
@ElectricCoffee
Copy link

Rust has changed a lot since you wrote this, you might want to update it to not confuse newcomers to the language

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment