如何将字符串转换为枚举? [英] How to convert a string to an enum?
问题描述
我的原始方法是要创建的称为 to_str()
的方法,该方法将返回切片,但由于该代码无法编译,我不确定这是正确的方法。
My original approach was to create method called to_str()
which will return a slice, but I am not sure that it is correct approach because this code doesn't compile.
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"),
}
}
推荐答案
正确的做法是实现 FromStr
。在这里,我与代表每个枚举变量的字符串文字进行匹配:
The correct thing is to implement FromStr
. Here, I'm matching against the string literals that represent each enum variant:
#[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);
}
要打印值,请实施 Display
或 Debug
(我得出了 Debug
此处)。实施 Display
还会为您提供 .to_string()
。
To print a value, implement Display
or Debug
(I've derived Debug
here). Implementing Display
also gives you .to_string()
.
在某些情况下,有些板条箱可以减少这种转换的乏味。 strum 就是这样的箱子:
In certain cases, there are crates that can reduce some of the tedium of this type of conversion. strum is one such crate:
use strum_macros::EnumString;
#[derive(Debug, EnumString)]
#[strum(serialize_all = "shouty_snake_case")]
enum WSType {
Ack,
Request,
Response,
}
这篇关于如何将字符串转换为枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!