Is there any way to simplify this code?
fn parse(line: &str) -> Result<(usize, f64), String> {
let mut it = line.split_whitespace();
let n = it.next().ok_or("Invalid line")?;
let n = n.parse::<usize>().map_err(|e| e.to_string())?;
let f = it.next().ok_or("Invalid line")?;
let f = f.parse::<f64>().map_err(|e| e.to_string())?;
Ok((n, f))
}
fn main() {
println!("Results: {:?}", parse("5 17.2").unwrap())
}
In real code, I need to parse 4 values per line, and it is boring to write .map_err(|e| e.to_string())
As I understand it, it is impossible to implement std::convert::Fromfor ParseIntError/ ParseFloatError→ String, because none of the types are defined in my code, am I right?
I see one way to simplify this code:
fn econv<E: ToString>(e: E) -> String {
e.to_string()
}
and use .map_err(econv). Are there any other possibilities to simplify my code?
source
share