当前位置: 首页 > 工具软件 > C2Rust > 使用案例 >

RUST笔记 :错误处理和try_from

松献
2023-12-01

改代码将十六进制字符串转化元祖结构,需要在toml文件中dependencies目录下引入thiserror,

知识点:from_str_radix将十六进制字符串切片转换成数字,

将标准库error转化成自定义error,

use std::convert::TryFrom;
use thiserror::Error;

#[derive(Debug, Error)]
enum RGBerror{
    #[error("hex colors must begin with hash (#)")]
    MissingHash,
    #[error("failed to parse hex digit: {0}")]
    ParseError(std::num::ParseIntError),
    #[error("invalid hex color length(should be 7)")]
    LengthError,
}

impl From<std::num::ParseIntError> for RGBerror {
    fn from(err: std::num::ParseIntError) -> Self {
        Self::ParseError(err)
    }
}

#[derive(Debug, Eq, PartialEq)]
struct RGB(u8, u8, u8);

impl TryFrom<&str> for RGB {
    type Error = RGBerror;
    fn try_from(hex: &str) ->Result<Self, RGBerror> {
        if !hex.starts_with('#') {
            return Err(RGBerror::MissingHash);
        }
        if hex.len() != 7 {
            return Err(RGBerror::LengthError);
        }
        let (r, g, b)  = (
            u8::from_str_radix(&hex[1..=2], 16)?,
            u8::from_str_radix(&hex[3..=4], 16)?,
            u8::from_str_radix(&hex[5..=6], 16)?,
        );
        Ok(Self(r, g, b))
    }
} 

fn main() {
    //Err.....ParseError
    let c1: Result<RGB, RGBerror> = "#opw222".try_into();
    //Err....MissingHash
    let c2: Result<RGB, RGBerror> = "000000".try_into();
    //Err....LengthError
    let c3: Result<RGB, RGBerror> = "#ffffffff".try_into();
    //Ok....RGB(255, 255, 255)
    let c4: Result<RGB, RGBerror> = "#ffffff".try_into();

}

 类似资料: