如何确保在编译时可以从特定函数返回每个枚举变量? [英] How to ensure every enum variant can be returned from a specific function at compile time?

查看:79
本文介绍了如何确保在编译时可以从特定函数返回每个枚举变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

enum Operation {
    Add,
    Subtract,
}

impl Operation {
    fn from(s: &str) -> Result<Self, &str> {
        match s {
            "+" => Ok(Self::Add),
            "-" => Ok(Self::Subtract),
            _ => Err("Invalid operation"),
        }
    }
}

我想确保在编译时,每个枚举变量都在 from 函数中处理。

I want to ensure at compile time that every enum variant is handled in the from function.

为什么我需要这个?例如,我可能添加了 Product 操作,却忘记了在 from 函数中处理这种情况:

Why do I need this? For example, I might add a Product operation and forget to handle this case in the from function:

enum Operation {
    // ...
    Product,
}

impl Operation {
    fn from(s: &str) -> Result<Self, &str> {
        // No changes, I forgot to add a match arm for `Product`.
        match s {
            "+" => Ok(Self::Add),
            "-" => Ok(Self::Subtract),
            _ => Err("Invalid operation"),
        }
    }
}

是否可以保证match表达式返回枚举的每个变体?如果不是,那么模仿此行为的最佳方法是什么?

Is it possible to guarantee that match expression returns every variant of an enum? If not, what is the best way to mimic this behaviour?

推荐答案

解决方案是生成整个枚举,变量和带有宏的翻译臂:

A solution would be to generate the whole enumeration, variants and translation arms with a macro:

macro_rules! operations {
    (
        $($name:ident: $chr:expr)*
    ) => {
        #[derive(Debug)]
        pub enum Operation {
            $($name,)*
        }
        impl Operation {
            fn from(s: &str) -> Result<Self, &str> {
                match s {
                    $($chr => Ok(Self::$name),)*
                    _ => Err("Invalid operation"),
                }
            }
        }
    }
}

operations! {
    Add: "+"
    Subtract: "-"
}

通过这种方式添加变体是微不足道的,并且您不会忘记解析。这也是一个非常干的解决方案。

This way adding a variant is trivial and you can't forget a parsing. It's also a very DRY solution.

很容易用其他函数(例如反翻译)扩展此结构,您以后肯定会用到,

It's easy to extend this construct with other functions (for example the inverse translation) that you'll surely need later and you won't have to duplicate the parsing char.

游乐场

这篇关于如何确保在编译时可以从特定函数返回每个枚举变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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