为什么“匹配”与Rust中的确切代码不匹配?

时间:2019-08-22 11:10:27

标签: rust rust-cargo

当我为枚举编写Display impl时,我编写的代码没有枚举类型,无论我在测试中给出什么值,它总是与第一个匹配,为什么?

我发现是否指定了Phase :: Add类型,那么它可以成功,但是为什么?

这将使测试失败:

#[derive(Clone, Debug)]
pub enum Phase {
    Add,
    Modify,
    Delete,
}

impl fmt::Display for Phase {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Add => write!(f, "Add"),
            Modify => write!(f, "Modify"),
            Delete => write!(f, "Delete"),
            _ => write!(f, "Unknown"),
        }
    }
}

#[test]
fn test_lifecycle_phase() {
    let mut phase = Phase::Modify;
    assert_eq!("Modify", phase.to_string());
    phase = Phase::Delete;
    assert_eq!("Delete", phase.to_string());
}

只能这样写,为什么?

#[derive(Clone, Debug)]
pub enum Phase {
    Add,
    Modify,
    Delete,
}

impl fmt::Display for Phase {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Phase::Add => write!(f, "Add"),
            Phase::Modify => write!(f, "Modify"),
            Phase::Delete => write!(f, "Delete"),
            _ => write!(f, "Unknown"),
        }
    }
}

#[test]
fn test_lifecycle_phase() {
    let mut phase = Phase::Modify;
    assert_eq!("Modify", phase.to_string());
    phase = Phase::Delete;
    assert_eq!("Delete", phase.to_string());
}

1 个答案:

答案 0 :(得分:3)

这是一个常见的陷阱。这是因为$current_date = $relase_date不是引用Add => ...,而是将Phase::Add的值绑定到新变量self。名称Add只是一个巧合,而模式Add和(新)变量Phase::Add是完全不同的结构。由于变量Add没有模式限制,因此始终匹配;变量AddModify仍未使用。

发现自己需要使用Delete,而不是Phase::Add