我有一个结构体需要按值传递、改变然后返回。我还想改变它的泛型类型,因为我使用这个状态来静态地确保函数调用的正确顺序,以实现安全的 FFI。 (示例:playground)
因为
use core::marker::PhantomData;
struct State1 {}
struct State2 {}
struct Whatever {}
struct X<State> {
a: Whatever,
b: Whatever,
c: Whatever,
_d: PhantomData<State>,
}
impl<State> Drop for X<State> {
fn drop(&mut self) {}
}
fn f(x: X<State1>) -> X<State2> {
let X { a, b, c, _d } = x;
//mutate a, b and c
X {
a,
b,
c,
_d: PhantomData,
} // return new instance
}
因为
X
实现了 Drop
,所以我得到:error[E0509]: cannot move out of type `X<State1>`, which implements the `Drop` trait
--> src/lib.rs:19:29
|
19 | let X { a, b, c, _d } = x;
| - - - ^ cannot move out of here
| | | |
| | | ...and here
| | ...and here
| data moved here
|
= note: move occurs because these variables have types that don't implement the `Copy` trait
我不想丢弃任何东西,因为并没有销毁x
,只是重新打包它。防止丢失x
的惯用方式是什么?