【问题标题】:How can I skip a call to write! when pattern matching for fmt::Display?我怎么能跳过写信的电话! fmt::Display 的模式匹配时?
【发布时间】:2018-04-30 12:55:53
【问题描述】:

考虑以下枚举:

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)?

【问题讨论】:

    标签: enums rust pattern-matching


    【解决方案1】:

    由于fmt 的返回类型是fmt::Result,您只需提供一个空的Ok(()) 值,以便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!(),但只有当您确定该值永远不需要为Displayed(否则会导致恐慌)时,这才是一个好主意。

    【讨论】:

    • 如果您不关心许多其他价值,您可以这样做_ => Ok(())
    猜你喜欢
    • 1970-01-01
    • 2013-06-22
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多