我怎么能跳过要写的电话!当fmt :: Display的模式匹配时?

时间:2018-04-30 12:55:53

标签: enums rust pattern-matching

考虑以下枚举:

enum SomeEnum { A, B, C }

以下fmt::Display实施:

impl fmt::Display for SomeEnum {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use SomeEnum::*;

        match *self {
            A => write!(f, "A"),
            B => write!(f, "B"),
            // I'm not interested in calling write! for C
        }
    }
}

模式匹配时是否可以跳过write!函数调用一个特定的枚举值(在本例中为C)?

1 个答案:

答案 0 :(得分:4)

由于fun <A> doSomething(block: A.Companion.() -> Unit): Unit { // bla bla bla A.block() } 的返回类型为fmt,您只需提供一个空的fmt::Result值,以使Ok(())的所有可能返回值具有相同的值type(和要编译的代码):

match

另一种方法是使用impl fmt::Display for SomeEnum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use SomeEnum::*; match *self { A => write!(f, "A"), B => write!(f, "B"), C => Ok(()), } } } ,但只有当您确定值永远不需要C => unreachable!()时,这是一个好主意(否则会引起恐慌)。