1

I'm trying to use an enum but I need string values to be saved in DB, Redis etc.

pub enum Place {
  Square = "1",
  House = "2",
  Office = "3",
  // and so on... Garage = "4",
}

But the compiler throws with:

error[E0308]: mismatched types
  |
3 |     Square = "1",
  |             ^^^ expected `isize`, found `&str`

error[E0308]: mismatched types
  |
4 |     House = "2",
  |            ^^^ expected `isize`, found `&str`

error[E0308]: mismatched types
  |
5 |     Office = "3",
  |            ^^^ expected `isize`, found `&str`

For more information about this error, try `rustc --explain E0308`.

Why?

What does it mean?

Fred Hors
  • 3,258
  • 3
  • 25
  • 71
  • Alternatively, you may be looking for how to [serialize your enum](https://stackoverflow.com/questions/52034764/how-do-i-serialize-an-enum-without-including-the-name-of-the-enum-variant) – Herohtar Sep 26 '22 at 14:00
  • Is there a way I can get the discriminant of each enum where I need it? – Fred Hors Sep 26 '22 at 14:02
  • https://doc.rust-lang.org/std/mem/fn.discriminant.html – Ömer Erden Sep 26 '22 at 14:08
  • Yeah. I saw it but is unstable and I cannot use it. It's crazy I can't do a simple thing like this. – Fred Hors Sep 26 '22 at 14:09
  • It is **const unstable** It can be used in stable but not as `const fn`, what I mean is: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=aa7d03b0e8217d4263592e5a3b7accf8 – Ömer Erden Sep 26 '22 at 14:12

1 Answers1

5

If what you need is a string representation of the values of your enum, then the work should be done in another trait implementation, namely Display. Implementing this trait allows your enum to implement the ToString trait for free.

You'd do something like:

use std::fmt;

pub enum Place {
    Square,
    House,
    Office,
}

impl fmt::Display for Place {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Square => "1",
                Self::House => "2",
                Self::Office => "3",
            }
        )
    }
}

fn main() {
    let place = Place::Office;
    println!("{place}"); // --> prints 3

    let s = place.to_string();
    println!("{s}"); // --> also prints 3
}

Playground link

SirDarius
  • 41,440
  • 8
  • 86
  • 100