Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add the to_string() functionality to an enum?

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?

like image 655
Akiner Alkan Avatar asked Oct 09 '18 12:10

Akiner Alkan


People also ask

Can enum have functions in TypeScript?

Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

Can enum have string values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Can I convert enum to string C++?

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.

Can we convert enum to string?

We can convert an enum to string by calling the ToString() method of an Enum.


1 Answers

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.

like image 192
ljedrz Avatar answered Nov 06 '22 21:11

ljedrz