我可以在Rust中将字符串转换为没有宏的枚举吗? [英] Can I convert a string to enum without macros in Rust?

查看:101
本文介绍了我可以在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.

是否可以在不编写自己的宏或从板条箱中导入一个宏的情况下获得此功能?

Is it possible to get this without writing my own macro or importing one from a crate?

推荐答案

编辑:答案是否定的. Rust不提供反射,通常将#[derive]用于此类任务.

The answer is no. Rust does not provide reflection and usually use #[derive] for that kind of tasks.

您可以使用板条箱 enum_derive

You can use the crates enum_derive and custom_derive to do what you want.

这是一个例子:

#[macro_use]
extern crate custom_derive;
#[macro_use]
extern crate enum_derive;

custom_derive! {
    #[derive(Debug, EnumFromStr)]
    enum Foo {
        Bar,
        Baz,
        Bat,
        Quux
    }
}

fn main() {
    let variable: Foo = "Bar".parse().unwrap();
    println!("{:?}", variable);
}

自定义EnumFromStrderive允许您使用parse方法获取Foo.

the derive of the custom EnumFromStr allows you to use the parse method to get a Foo.

这篇关于我可以在Rust中将字符串转换为没有宏的枚举吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆