【发布时间】:2015-06-23 16:30:48
【问题描述】:
我在一个结构上matching,想使用一个匹配守卫。但是,该结构是可变的,并且匹配臂左侧的绑定变量似乎会导致单独的借用。然后这会触发编译错误,因为当可变借用未完成时,您不能有第二次借用(可变或不可变)。
struct A(u8);
impl A {
fn is_awesome(&self) -> bool { true }
}
struct Container(A);
impl Container {
fn update(&mut self) {}
fn do_a_thing(&mut self) {
match *self {
Container(ref a) if a.is_awesome() => self.update(),
_ => {},
}
}
}
fn main() {}
error[E0502]: cannot borrow `*self` as mutable because `self.0` is also borrowed as immutable
--> src/main.rs:14:51
|
14 | Container(ref a) if a.is_awesome() => self.update(),
| ----- ^^^^ mutable borrow occurs here
| |
| immutable borrow occurs here
15 | _ => {},
16 | }
| - immutable borrow ends here
我目前的解决方法是在我的比赛之前复制计算比赛守卫的逻辑,然后我可以只使用布尔值作为我的比赛守卫。对于明显的代码重复问题,这并不令人满意:
fn do_a_thing(&mut self) {
let awesome = match *self {
Container(ref a) => a.is_awesome(),
};
match *self {
Container(..) if awesome => self.update(),
_ => {},
}
}
【问题讨论】:
-
我自己会把
match self { &mut Container(ref a) => … }改写成let a = &self.0; …。 -
@ChrisMorgan 是的,我也是。使用模式匹配而不添加枚举或其他嵌套层以试图保持示例较小是一种自负。
-
(在这种情况下,流行的样式也是
match *self { Container(ref a) => … },以取出匹配主题中的任何引用而不是分支模式。) -
@ChrisMorgan 很好,这是我在围栏上试验的剩余物!
标签: pattern-matching rust