Skip to content

Instantly share code, notes, and snippets.

@brendanzab
Forked from erickt/gist:3956374
Created October 26, 2012 01:13
Show Gist options
  • Save brendanzab/3956434 to your computer and use it in GitHub Desktop.
Save brendanzab/3956434 to your computer and use it in GitHub Desktop.
map_cast Rust macro
use to_str::ToStr;
macro_rules! map_cast(
(~[$($elems:expr),+] -> $T:ty) => (~[$($elems as $T),+]);
(@[$($elems:expr),+] -> $T:ty) => (@[$($elems as $T),+]);
($arr:expr -> $T:ty) => ($arr.map(|a| *a as $T));
)
fn main() {
let arr1 = map_cast!(~[1, 2.5] -> ToStr);
io::println(fmt!("%?", arr1.map(|x| x.to_str())));
let arr2 = map_cast!(@[1, 2.5] -> ToStr);
io::println(fmt!("%?", arr2.map(|x| x.to_str())));
let arr3 = ~[1.0, 2.5];
io::println(fmt!("%?", map_cast!(arr3 -> ToStr).map(|x| x.to_str())));
let char_arr = @['4', 'b', '&'];
io::println(fmt!("%?", map_cast!(char_arr -> u8)));
io::println(fmt!("%?", map_cast!(~[0.5, 1.0, 1.5] + ~[2.0, 2.5, 3.0] -> int)));
// we run into the float casting problem here as well
// io::println(fmt!("%?", map_cast!(~[0.5, 1, 1.5] + ~[2, 2.5, 3] -> int)));
// the 'map' trait is not implemented for unique strings
// io::println(fmt!("%?", map_cast!(~"xyz" + ~"23" -> u8)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment