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"); }
)
}
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."); }
})
}
Rust has changed a lot since you wrote this, you might want to update it to not confuse newcomers to the language