11

I am trying to create Error enums that implement to_string(). I have tried to derive(Debug) for them but it doesn't seem to be enough.

Here is the enum that I am working on:

#[derive(Debug, Clone)]
pub enum InnerError {
    InnerErrorWithDescription(String),
}

#[derive(Debug, Clone)]
pub enum OuterError {
    OuterErrorWithDescription(String),
}

What I am trying to make is:

// result type <T,InnerErrorWithDescription>
result.map_err(|err| { Error::OuterErrorWithDescription(err.to_string())}) // .to_string() is not available

I could not manage to convert InnerError enum type to OuterError.

What should I change to implement it?

I have made an example for writing enum types and their values' here:

Rust Playground

But, still I had to specify the type and it's description in match case, are there any more generic implementation?

Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68

1 Answers1

13

Your enum should implement Display; from ToString docs:

This trait is automatically implemented for any type which implements the Display trait. As such, ToString shouldn't be implemented directly: Display should be implemented instead, and you get the ToString implementation for free.

Edit: I have adjusted your playground example; I think you might be after something like this.

ljedrz
  • 20,316
  • 4
  • 69
  • 97
  • This example is useful, but still we need to specify the to_string description as hardcoded. Can we make a dynamically generated string description containing the enum type and the description of it inside of the formatter? I am looking for something like: write!(f,"{} , {} ",self.type,self.desc) – Akiner Alkan Oct 09 '18 at 13:56
  • @AkinerAlkan in that case you might be interested in an error struct rather than an enum: [playground](https://play.rust-lang.org/?gist=488a9117d81e61b5ae02afed538b11d1&version=stable&mode=debug&edition=2015). – ljedrz Oct 09 '18 at 14:05