'Get matched expression inside match block
Is it possible to access the matched expression inside a match block?
Considering this example, with what should I replace 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())
};
}
Solution 1:[1]
I would simply extract the expression before, and reuse the binding in the error message.
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")
*/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | prog-fh |
