macro_rules! match_cast {
($any:ident { $( $bind:ident as $patt:ty => $body:block $(,)? )+ }) => { ... };
}Expand description
Match through different types.
Example:
use std::any::Any;
use chrono::NaiveDate;
use claudiofsr_lib::match_cast;
let opt_u8: Option<u8> = None;
let opt_u32: Option<u32> = Some(5);
let float64: f64 = 32.00870000;
let string: String = String::from("foo bar baz");
let opt_naivedate: Option<NaiveDate> = NaiveDate::from_ymd_opt(2015, 3, 14);
// With std::any::Any it is possible to obtain a vector with different types:
let values: Vec<&dyn Any> = vec![
&opt_u8,
&opt_u32,
&float64,
&string,
&opt_naivedate,
];
// Get lengths of all items in the vector.
let lengths: Vec<usize> = values
.into_iter()
.map(|value| {
let opt_value_len: Option<usize> = match_cast!( value {
val as Option<u8> => {
val.as_ref().map(|s| s.to_string().chars().count())
},
val as Option<u32> => {
val.as_ref().map(|s| s.to_string().chars().count())
},
val as f64 => {
Some(val.to_string().chars().count())
},
val as String => {
Some(val.chars().count())
},
val as Option<NaiveDate> => {
// eprintln!("val: {val:?}"); // Some(2015-03-14)
val.as_ref().map(|date| date.to_string().chars().count())
}
});
opt_value_len.unwrap_or(0)
})
.collect();
assert_eq!(
lengths,
[0, 1, 7, 11, 10]
);Font: https://github.com/therustmonk/match_cast/blob/master/src/lib.rs