有没有办法让merge
函数使用&mut self
,使用内部枚举值,并在合并时将其推送到新的向量上?我一直在和编译器抗争--PEBKAC,但在哪里呢?
如果这是不可能的,可以通过在Val
上实现Clone
特征来修复它吗?(但不能修复Copy
特征!)
struct Val();
enum Foo {
One(Val),
Many(Vec<Val>),
}
impl Foo {
pub fn merge(&mut self, other: Self) {
match (*self, other) {
// ^^^^^
// move occurs because `*self` has type `Foo`, which does not implement the `Copy` trait
// cannot move out of `*self` which is behind a mutable reference
//
(Self::One(a), Self::One(b)) => *self = Self::Many(vec![a, b]),
(Self::One(a), Self::Many(mut b)) => {
b.insert(0, a);
*self = Self::Many(b)
}
(Self::Many(mut a), Self::One(b)) => {
a.push(b);
}
(Self::Many(mut a), Self::Many(b)) => {
a.extend(b);
}
};
}
}