Enums 我怎么能不打电话写信呢!fmt::Display的模式匹配何时开始?

Enums 我怎么能不打电话写信呢!fmt::Display的模式匹配何时开始?,enums,rust,pattern-matching,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"),

考虑以下枚举:

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
        }
    }
}

是否可以跳过
写入C
)的code>函数调用?

由于
fmt
的返回类型是
fmt::Result
,您只需提供一个空的
Ok(())
值,以便
match
的所有可能返回值具有相同的类型(以及要编译的代码):


另一种方法是使用
C=>unreachable!()
,但这是一个好主意,只有当您确定值永远不需要显示时(否则会引起恐慌)。

由于
fmt
的返回类型是
fmt::Result
,您只需要提供一个空的
Ok(())
value,以便所有可能的
match
返回值具有相同的类型(以及要编译的代码):


另一种方法是使用
C=>unreachable!()
,但这是一个好主意,前提是您确定值永远不需要显示(否则会引起恐慌)。

如果您不关心许多其他值,您可以执行
\Ok(())
如果您不关心许多其他值,您可以执行
\u=>Ok(())
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(()),
        }
    }
}