<分区>
有没有一种方法可以让merge
函数使用&mut self
,消耗内部枚举值并在合并时将其插入新的Vector?我一直在与编译器抗争——PEBKAC,但是在哪里呢?
如果这不可能,是否可以通过在 Val
上实现 Clone
trait 来解决这个问题? (但不是 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);
}
};
}
}