当我为枚举编写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());
}
答案 0 :(得分:3)
这是一个常见的陷阱。这是因为$current_date = $relase_date
不是引用Add => ...
,而是将Phase::Add
的值绑定到新变量self
。名称Add
只是一个巧合,而模式Add
和(新)变量Phase::Add
是完全不同的结构。由于变量Add
没有模式限制,因此始终匹配;变量Add
和Modify
仍未使用。
发现自己需要使用Delete
,而不是Phase::Add
。