类似这样的宏
macro_rules! batch_print {
// 基本情形:
($x:expr,u32) => (print!("{}(u32)",$x));
($x:expr,i32) => (print!("{}(i32)",$x));
($x:expr,f32) => (print!("{}(f32)",$x));
($x:expr,&str) => (print!("{}(str)",$x));
($x:expr,_) => (print!("{}(other)",$x));
// `$x` 后面跟着至少一个 `$y,`
($x:expr, $($y:expr),+) => (
// 对尾部的 `$y` 调用 `batch_print!`
//batch_print!($x, find_min!($($y),+))
batch_print!($x);
batch_print!($($y),+);
)
}
能实现吗?求大神指点
1
共 3 条评论, 1 页
评论区
写评论注意使用md语法。
感谢指点,已经达到我的要求了,我稍微改了一下: fn print_single(arg: T) where T: std::fmt::Debug, { let arg_type_name = std::any::type_name::(); print!("{:?}({})", arg, arg_type_name) }
macro_rules! print_with_type { () => (println!()); ( $($arg:expr),) => { $(print_single($arg);) print!("\n") } }
fn main() { print_with_type!("Rust"," is"," fun".to_string()); let c=299792458; print_with_type!("c=",c,"m/s"); }
fn format_to_string<T>(arg: T) -> String where T: std::fmt::Debug, { let arg_type_name = std::any::type_name::<T>(); format!("{:?}({})", arg, arg_type_name) } macro_rules! myprintln { () => (println!()); ($fmt:tt, $($arg:expr),* $(,)?) => { println!("{}", std::format_args!( $fmt, $(format_to_string($arg)),* ) ); } } fn main() { // empty line myprintln!(); let n = 1; // simple myprintln!("{}", n); // reference myprintln!("{}", &n); // tailing comma myprintln!("{}", n,); let s = "abc"; // &str myprintln!("{}", s); // string myprintln!("{}", s.to_string()); // tuple let t = (1, 2, 3); myprintln!("{}, {}, {}", n, s, t); // vec let v = vec![1, 2, 3]; myprintln!("{}", v.repeat(2)); // &[i32] myprintln!("{}", &v[..]); }
还是有缺点,主要是没法处理 {} 和 {:?} {:#?},现在全都是按照 {:?} 做的。要做应该也可以,但是得重写
std::format_args
,比较麻烦。