dtolnay / thiserror

derive(Error) for struct and enum error types

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Delegate display to a function

Noodlez1232 opened this issue · comments

It'd be very nice to be able to delegate the display of an error to a function.

Example code:

use std::fmt;
#[derive(Debug, Error)]
pub struct TestError {
    #[error("Display error: {0}")]
    GenDisplay(usize),
    #[display(disp_func)]
    UserDisplay(usize, uize),
}

// It'd be useful to have a similar function signature to the Display impl
fn disp_func(f: &fmt::Formatter<'_T>, err_inside_0: usize, err_inside_1: usize) -> fmt::Result {
    write!(f, "Err1: {}, Err2: {}", err_inside_0, err_inside_1)
}

I think I would prefer not to support this. You can handwrite the Display impl though:

use std::fmt::{self, Display};

impl Display for TestError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TestError::GenDisplay(x) => write!(f, "Display error: {}", x),
            TestError::UserDisplay(err_inside_0, err_inside_1) => disp_func(f, *err_inside_0, *err_inside_1),
        }
    }
}