【发布时间】:2018-06-02 04:33:59
【问题描述】:
我想从模式匹配的可变引用中提取一个值并丢弃旧的。
这是我想出的一个最小的例子:
fn main() {
#[derive(Debug)]
enum D<A> {
E1(A),
E2(A, A),
};
trait Zero<A> {
fn zero() -> A;
}
impl<A> D<A> {
pub fn push2(&mut self, e: A) {
match self {
D::E1(e1) => {
*self = D::E2(*e1, e);
}
_ => unimplemented!(),
}
}
pub fn push(&mut self, e: A)
where
A: Zero<A>,
{
match self {
D::E1(e1) => {
let mut r = A::zero();
std::mem::swap(&mut r, e1);
*self = D::E2(e, r);
}
_ => unimplemented!(),
};
}
}
impl Zero<i32> for i32 {
fn zero() -> i32 {
0
}
}
let mut d = D::E1(10);
d.push(11);
println!("{:?}", d);
}
push2 失败:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:17:39
|
17 | *self = D::E2(*e1, e);
| ^^^ cannot move out of borrowed content
我想在不需要 Copy 特征的情况下实现这一点,因为我在里面有一些盒装类型,理想情况下希望消除对虚拟变量 (A::zero()) 的需求。
【问题讨论】:
-
有人建议我使用 std::mem::replace 而不是 std::mem::swap ,这让事情变得不那么冗长,但它仍然是实现结果的丑陋方式。跨度>