我需要在每一行上解析一个文件
<string><space><int><space><float>
例如
abce 2 2.5
在C中,我会做:
scanf("%s%d%f", &s, &i, &f);
在Rust中,我怎样才能轻松且惯用地做到这一点?
我需要在每一行上解析一个文件
<string><space><int><space><float>
例如
abce 2 2.5
在C中,我会做:
scanf("%s%d%f", &s, &i, &f);
在Rust中,我怎样才能轻松且惯用地做到这一点?
标准库不提供此功能.你可以用宏自己写.
macro_rules! scan {
( $string:expr, $sep:expr, $( $x:ty ),+ ) => {{
let mut iter = $string.split($sep);
($(iter.next().and_then(|word| word.parse::<$x>().ok()),)*)
}}
}
fn main() {
let output = scan!("2 false fox", char::is_whitespace, u8, bool, String);
println!("{:?}", output); // (Some(2), Some(false), Some("fox"))
}
宏的第二个输入参数可以是a&;str、char或相应的闭包/函数.指定的类型必须实现FromStr特性.
请注意,我很快就把它放在了一起,所以它还没有经过彻底的测试.