在匹配块中获取匹配的表达式
Get matched expression inside match block
是否可以在匹配块中访问匹配的表达式?
考虑到这个例子,我应该用什么替换 HERE
?
fn fetch_u32(args: &mut Vec<&str>) -> Result<u32,String> {
match args.remove(0).parse::<u32>() {
Ok(result) => Ok(result),
Err(_) => Err("Argument '" + HERE + "' is not of type uint32".to_string())
};
}
我会简单地提取之前的表达式,并在错误消息中重用绑定。
fn fetch_u32(args: &mut Vec<&str>) -> Result<u32, String> {
let a = args.remove(0);
match a.parse::<u32>() {
Ok(result) => Ok(result),
Err(_) => Err(format!("Argument '{}' is not of type uint32", a)),
}
}
fn main() {
let mut args = vec!["123", "bla", "456", "hop"];
while !args.is_empty() {
let r = fetch_u32(&mut args);
println!("{:?}", r);
}
}
/*
Ok(123)
Err("Argument 'bla' is not of type uint32")
Ok(456)
Err("Argument 'hop' is not of type uint32")
*/
是否可以在匹配块中访问匹配的表达式?
考虑到这个例子,我应该用什么替换 HERE
?
fn fetch_u32(args: &mut Vec<&str>) -> Result<u32,String> {
match args.remove(0).parse::<u32>() {
Ok(result) => Ok(result),
Err(_) => Err("Argument '" + HERE + "' is not of type uint32".to_string())
};
}
我会简单地提取之前的表达式,并在错误消息中重用绑定。
fn fetch_u32(args: &mut Vec<&str>) -> Result<u32, String> {
let a = args.remove(0);
match a.parse::<u32>() {
Ok(result) => Ok(result),
Err(_) => Err(format!("Argument '{}' is not of type uint32", a)),
}
}
fn main() {
let mut args = vec!["123", "bla", "456", "hop"];
while !args.is_empty() {
let r = fetch_u32(&mut args);
println!("{:?}", r);
}
}
/*
Ok(123)
Err("Argument 'bla' is not of type uint32")
Ok(456)
Err("Argument 'hop' is not of type uint32")
*/