如何在枚举中使用字符串值并避免“预期的`isize`,找到的`&str`”?

Fre*_*ors 1 rust

我正在尝试使用,enum但我需要将字符串值保存在数据库、Redis 等中。

pub enum Place {
  Square = "1",
  House = "2",
  Office = "3",
  // and so on... Garage = "4",
}
Run Code Online (Sandbox Code Playgroud)

但编译器抛出:

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`.
Run Code Online (Sandbox Code Playgroud)

为什么?

这是什么意思?

Sir*_*ius 5

如果您需要的是枚举值的字符串表示形式,那么这项工作应该在另一个特征实现中完成,即DisplayToString实现此特征允许您的枚举免费实现该特征。

你会做类似的事情:

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
}
Run Code Online (Sandbox Code Playgroud)

游乐场链接