我可以在 Rust 中将字符串转换为没有宏的枚举吗? [英] Can I convert a string to enum without macros in Rust?
问题描述
例如,如果我有这样的代码:
For example, if I have code like:
enum Foo {
Bar,
Baz,
Bat,
Quux
}
impl Foo {
from(input: &str) -> Foo {
Foo::input
}
}
这显然会失败,因为 input
不是 Foo 的方法.我可以手动输入:
This will obviously fail because input
is not a method of Foo. I can manually type:
from(input: &str) -> Foo {
match(input) {
"Bar" => Foo::Bar,
// and so on...
}
}
但我没有得到自动的便利.
but I'm not getting the automatic convenience.
看起来 Java 在枚举上有一个 字符串查找函数 用于此特定目的.
It looks like Java has a string lookup function on enums for this specific purpose.
是否有可能在不编写我自己的宏或从 crate 中导入宏的情况下获得它?
Is it possible to get this without writing my own macro or importing one from a crate?
推荐答案
你应该实现 std::str::FromStr 特征.
use std::str::FromStr;
#[derive(Debug, PartialEq)]
enum Foo {
Bar,
Baz,
Bat,
Quux,
}
impl FromStr for Foo {
type Err = ();
fn from_str(input: &str) -> Result<Foo, Self::Err> {
match input {
"Bar" => Ok(Foo::Bar),
"Baz" => Ok(Foo::Baz),
"Bat" => Ok(Foo::Bat),
"Quux" => Ok(Foo::Quux),
_ => Err(()),
}
}
}
fn main() {
// Use it like this
let f = Foo::from_str("Baz").unwrap();
assert_eq!(f, Foo::Baz);
}
代码生成(又称自动便利)和反射通常需要付出代价.在实践中,您最终不太可能得到多个枚举变体.
Code-generation (aka automatic convenience) and reflections usually bear a cost. In practice, it is unlikely that you will end up with more than a few enum variants.
在游乐场
这篇关于我可以在 Rust 中将字符串转换为没有宏的枚举吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!