What is the most idiomatic way to merge two error types?

前端 未结 2 711
暖寄归人
暖寄归人 2020-12-21 08:41

I have a type Foo whose methods may "raise" errors of an associated type Foo::Err.

pub trait Foo {
    type Err;
    
             


        
2条回答
  •  礼貌的吻别
    2020-12-21 09:05

    Typically you don't do a "merge", but instead use nested errors, like this.

    enum IntError {
        Overflow,
        Underflow
    }
    
    enum StrError {
        TooLong,
        TooShort,
    }
    
    enum GenericError {
        Int(IntError),
        Str(StrError),
    }
    
    impl From for GenericError {
        fn from(e: IntError) -> Self {
            GenericError::Int(e)
        }
    }
    
    impl From for GenericError {
        fn from(e: StrError) -> Self {
            GenericError::Str(e)
        }
    }
    

提交回复
热议问题