【问题标题】:How to convert a string to an enum?如何将字符串转换为枚举?
【发布时间】:2016-07-30 05:56:06
【问题描述】:

我的 original approach 是创建名为 to_str() 的方法,该方法将返回一个切片,但我不确定这是正确的方法,因为此代码无法编译。

enum WSType {
    ACK,
    REQUEST,
    RESPONSE,
}

impl WSType {
    fn to_str(&self) -> &str {
        match self {
            ACK => "ACK",
            REQUEST => "REQUEST",
            RESPONSE => "RESPONSE",            
        }
    }
}

fn main() {
    let val = "ACK";
    // test
    match val {
        ACK.to_str() => println!("ack"),
        REQUEST.to_str() => println!("ack"),
        RESPONSE.to_str() => println!("ack"),
        _ => println!("unexpected"),
    }
}

【问题讨论】:

  • @Shepmaster 是的,你是对的,它无法编译。我想我应该在原帖中提到它。我试图将随机字符串切片匹配到特定的枚举。

标签: enums casting rust


【解决方案1】:

正确的做法是实现FromStr。在这里,我匹配代表每个枚举变体的字符串文字:

#[derive(Debug)]
enum WSType {
    Ack,
    Request,
    Response,
}

impl std::str::FromStr for WSType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ACK" => Ok(WSType::Ack),
            "REQUEST" => Ok(WSType::Request),
            "RESPONSE" => Ok(WSType::Response),
            _ => Err(format!("'{}' is not a valid value for WSType", s)),
        }
    }
}

fn main() {
    let as_enum: WSType = "ACK".parse().unwrap();
    println!("{:?}", as_enum);

    let as_enum: WSType = "UNKNOWN".parse().unwrap();
    println!("{:?}", as_enum);
}

要打印一个值,请实现DisplayDebug(我在这里派生了Debug)。实现Display 也会给你.to_string()


在某些情况下,有些板条箱可以减少此类转​​换的一些乏味。 strum 就是这样一个箱子:

use strum_macros::EnumString;

#[derive(Debug, EnumString)]
#[strum(serialize_all = "shouty_snake_case")]
enum WSType {
    Ack,
    Request,
    Response,
}

【讨论】:

  • 感谢@Shepmaster,它看起来很完美。
猜你喜欢
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 2015-06-10
  • 1970-01-01
相关资源
最近更新 更多