[英]How can I simplify converting errors into strings multiple times in a function?
有沒有辦法簡化這段代碼?
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())
}
在實際代碼中,我需要在行中解析4個值,編寫.map_err(|e| e.to_string())
很無聊
據我了解,不可能實現std::convert::From
for ParseIntError
/ ParseFloatError
- > String
,因為我的代碼中沒有定義任何類型,我是對的嗎?
我看到一種簡化此代碼的方法:
fn econv<E: ToString>(e: E) -> String {
e.to_string()
}
並使用.map_err(econv)
。 還有其他選項來簡化我的代碼嗎?
好吧,一個不太可怕的選擇就是創建一個抽象重復的函數:
use std::fmt::Display;
use std::iter::Iterator;
use std::str::FromStr;
fn parse_next<'a, Target, T>(it: &mut T) -> Result<Target, String>
where
T: Iterator<Item = &'a str>,
Target: FromStr,
<Target as FromStr>::Err: Display
{
it.next().ok_or("Invalid line")?.parse::<Target>().map_err(|e| e.to_string())
}
fn parse(line: &str) -> Result<(usize, f64), String> {
let mut it = line.split_whitespace();
Ok((parse_next(&mut it)?, parse_next(&mut it)?))
}
fn main() {
println!("Results: {:?}", parse("5 17.2").unwrap())
}
我將介紹一種專用的錯誤類型。 如果需要 ,我會在之后將錯誤轉換為字符串:
#[macro_use]
extern crate quick_error;
quick_error! {
#[derive(Debug)]
pub enum Error {
InvalidLine {}
Int(err: std::num::ParseIntError) {
from()
}
Float(err: std::num::ParseFloatError) {
from()
}
}
}
fn parse_inner(line: &str) -> Result<(usize, f64), Error> {
let mut it = line.split_whitespace();
let n = it.next().ok_or(Error::InvalidLine)?;
let n = n.parse()?;
let f = it.next().ok_or(Error::InvalidLine)?;
let f = f.parse()?;
Ok((n, f))
}
fn parse(line: &str) -> Result<(usize, f64), String> {
parse_inner(line).map_err(|e| e.to_string())
}
fn main() {
println!("Results: {:?}", parse("5 17.2").unwrap())
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.