繁体   English   中英

如何在函数中多次简化将错误转换为字符串?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM