首页 > 其他分享 >[Rust] Using Box<dyn error::Error>> return one of miultiple error types at runtime

[Rust] Using Box<dyn error::Error>> return one of miultiple error types at runtime

时间:2024-03-04 21:23:37浏览次数:16  
标签:Box CreationError return fmt use miultiple Negative error PositiveNonzeroInteger

use std::error;
use std::fmt;
use std::num::ParseIntError;

fn main() -> Result<(), Box<dyn error::Error>> {
    let pretend_user_input = "42";
    let x: i64 = pretend_user_input.parse()?;
    println!("output={:?}", PositiveNonzeroInteger::new(x)?);
    Ok(())
}

#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);

#[derive(PartialEq, Debug)]
enum CreationError {
    Negative,
    Zero,
}

impl PositiveNonzeroInteger {
    fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
        match value {
            x if x < 0 => Err(CreationError::Negative),
            x if x == 0 => Err(CreationError::Zero),
            x => Ok(PositiveNonzeroInteger(x as u64)),
        }
    }
}

// This is required so that `CreationError` can implement `error::Error`.
impl fmt::Display for CreationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let description = match *self {
            CreationError::Negative => "number is negative",
            CreationError::Zero => "number is zero",
        };
        f.write_str(description)
    }
}

impl error::Error for CreationError {}

 

标签:Box,CreationError,return,fmt,use,miultiple,Negative,error,PositiveNonzeroInteger
From: https://www.cnblogs.com/Answer1215/p/18052716

相关文章

  • 从__builtin_eh_return看callee saved register
    问题C++的异常处理看起来是一个比较神奇的功能,能够在运行时穿越堆栈,从异常发生位置直达异常处理位置。通过gcc的代码可以看到,这个堆栈回溯的一个关键步骤是这个宏,其中又使用了gcc的内置指令__builtin_eh_return。网上关于__builtin_eh_return这个内置函数的资料较少,结合gcc的源代......
  • UnicheckBox左侧选择框显示问题!!!
    UnicheckBox左侧选择框有时显示、有时不显示,是一个BUG啊。试了后发现,改变一下程序uses列表顺序,可解决这个问题:unitabcc;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,DateUtils,uniPanel,uniGUIBaseClasses,uniGUIFrame,uni......
  • MapBox信息补填
    Mapbox目前仍然不允许国内用户注册(但可以登录使用,奇怪了),近期已注册的账号也让补充一些信息,很多人不知道怎么填写,为源GIS来帮您详细讲解说明一下。问题描述2024年Mapbox官网注册账号发生一些变化,注册时需要填写账号的类别是个人使用还是商业用途。以前注册过的账号,登录时,强制要......
  • Spectrum Digitizer NETBOX|LXI数据采集|瞬态记录仪
    产品简介:♦DigitizerNETBOX配有4/8通道♦512MSamples(1GB)采集内存♦或16通道2×512MSamples采集内存Ethernet/LXI接口,16位数字化仪,单端/真正差分输入更多信息请加weixin-pt890111获取数字化仪硬件在DigitizerNETBOX内部安装已经被成功证明了的Spectrum数字化仪的硬件部......
  • JAVA基础:引用类型参数传递的相关案例(数组的传递) 方法重载 return关键字
    packagecom.itheima.Method;publicclassMethod6{publicstaticvoidmain(String[]args){int[]arrs=newint[]{2,5,6,4};printArray(arrs);}publicstaticvoidprintArray(int[]arr){if(arr!=null){System.out......
  • Excel批量插入checkbox的宏代码
    来源网络,作为个人记录使用手动在excel中添加勾选框不复杂,但是添加多个的时候会很麻烦,特别是在做数据分析时,选择框属性应该绑定在对应单元格下,使用普通的填充方式无法到达要求,因此使用VBA宏命令批量添加.1Sub添加复选框()2'标题'3Application.ScreenUpdating=f......
  • WPF DataGrid下的单元格嵌入CheckBox列表
    <DataGridWidth="auto"Height="auto"AutoGenerateColumns="False"CanUserAddRows="False"GridLinesVisibility="All">        <DataGrid.Columns><DataGridTempla......
  • Openlayer加载mapboxgl矢量图层
    注意Openlayer的版本Openlayer是支持直接加载矢量图层的,如下图层会没有样式渲染<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0&q......
  • idea 报错 Directory '/Users/codes/other/tool-box/tool-box' does not contain a Gr
    idea报错Directory'/Users/codes/other/tool-box/tool-box'doesnotcontainaGradlebuild. Gradlebuild时提示IDEAThespecifiedprojectxxxxdirectorydoesnotexist.前提因为我之前想自己开发一个将sql文件格式化的插件,中途放弃直接用程序写完了,插件开发时用的......
  • UE5工具管理插件——UserToolBox
    视频链接:https://www.bilibili.com/video/BV1Vu4m1N75U/?spm_id_from=333.1007.tianma.41-3-161.click&vd_source=0b48a4de5d48210298dd8b91fa633329UserToolBoxUserToolBox是一个可以管理蓝图脚本和Python命令,python脚本的插件1启动插件2创建选项卡3修改选项卡的名字可......