作为Rust的新手,我遇到了两种似乎都可以的用于引用类型匹配的方法。
我定义了一个枚举:
我定义了一个枚举:
enum Color {
Red,
Yellow,
Green,
Teal,
Blue,
Purple,
}
我希望实现一个函数,可以在此枚举类型的实例的&self
引用上工作。
我可以看到两种编写这个函数的方式:
impl Color {
// Approach #1: Match the reference, using references in each pattern
fn contains_red(&self) -> bool {
match self {
&Color::Red => true,
&Color::Yellow => true,
&Color::Purple => true,
_ => false,
}
}
// Approach #2: Dereference &self and match the patterns directly
fn contains_blue(&self) -> bool {
match *self {
Color::Blue => true,
Color::Teal => true,
Color::Purple => true,
_ => false,
}
}
}
我本以为解引用&self
会被视为移动,并且如果我连续两次调用color.contains_blue()
,就会导致错误,但事实并非如此。
这些方法在功能上是否相同? 如果我匹配更复杂的对象,其中一个方法是否会失败?
Color
不是Copy
,对吧? - Matthieu M.