gpt4 book ai didi

reference - 当旧的枚举被丢弃时,有没有一种方法可以从 &mut 枚举中提取值?

转载 作者:行者123 更新时间:2023-11-29 08:18:26 24 4
gpt4 key购买 nike

<分区>

我想从模式匹配的可变引用中提取一个值并丢弃旧的。

这是我想出的一个最小示例:

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);
}

playground

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() )。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com