freemoon
V2EX  ›  Rust

[Rust] 关于三种 return Error trait 的区别是什么,如何辨别使用场景?

  •  
  •   freemoon · Oct 2, 2022 · 2622 views
  •   You need to sign in to view this topic
    This topic created in 1515 days ago, the information mentioned may be changed or developed.
    use std::error::Error;
    use std::fmt::{Debug, Display, Formatter};
    
    pub fn test() {
        #[derive(Debug)]
        struct MyErr;
        impl Display for MyErr {
            fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
                f.write_str("MyErr happened")
            }
        }
        impl Error for MyErr {}
    
        // 三种返回 error 方式的区别是什么? 待解答
    
        fn f3() -> Result<i32, impl Error> {
            Result::Err(MyErr)
        }
        fn f3_1() -> Result<i32, Box<dyn Error>> {
            Result::Err(Box::new(MyErr))
        }
        fn f3_2() -> Result<i32, &'static dyn Error> {
            Result::Err(&MyErr)
        }
    }
    

    求大佬解答,给个链接也行~

    4 replies  •  2022-10-03 06:59:54 +08:00
    freemoon
    freemoon
    OP
    Oct 2, 2022
    1
    111
    gwy15
    gwy15
    Oct 2, 2022❤️1
    2
    第一种是返回一个实现了 StdError trait 的类型,不建议这么写
    第二种是返回 trait object ,可以这么写,适用于非常简单的场景
    第三种几乎永远不会用。

    你的 Error 实现方式也是有问题的,现在的做法 库 一般会用 thiserror ,应用 /业务一般用 anyhow
    freemoon
    freemoon
    OP
    Oct 2, 2022
    3
    @gwy15 谢谢,我研究一下
    DTCPSS
    DTCPSS
    Oct 3, 2022 via iPhone
    4
    impl Error 应该会给每一种 Error 生成一份代码,用空间换速度。一般用 2 。或者直接用 thiserror 库做库异常处理,用 anyhow 库做应用异常处理。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1255 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:48 · PVG 07:48 · LAX 15:48 · JFK 18:48
    ♥ Do have faith in what you're doing.