RUST笔记 :错误处理和try_from

改代码将十六进制字符串转化元祖结构,需要在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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值