假设我想写这样的代码:
struct Inspector<'a>(&'a u8);
struct Foo<'a> {
value: Box<u8>,
inspector: Option<Inspector<'a>>,
}
fn main() {
let mut foo = Foo { value: Box::new(0), inspector: None };
foo.inspector = Some(Inspector(&foo.value));
}
Run Code Online (Sandbox Code Playgroud)
目前,Rust 编译器允许我这样做,只要我不Drop为Inspector.
如果我添加一个,则会出现以下编译时错误:
foo.value还借的时候掉了。Borrow 可能会在
foo被删除并运行析构函数时使用Foo<'_>
这显然是正确的。事实上,我已经从nomicon 中提取了这个例子。
现在,这是我的问题。假设我有一个奇怪的 a 实现,它的类型参数中Box没有任何T参数。
/// An heap-allocated `T` without generic parameters.
struct MyBox {
data: NonNull<u8>,
/// SAFETY:
/// Caller must ensure the value will not be
/// …Run Code Online (Sandbox Code Playgroud) 我正在使用两个独立的功能。
// This structure is not `Clone`.
struct MyStruct;
fn take_owned(s: MyStruct) -> MyStruct {
// Do things
s
}
fn take_mut(s: &mut MyStruct) {
*s = take_owned(s /* problem */);
}
Run Code Online (Sandbox Code Playgroud)
我想了一个解决方案,但我不确定它是否合理:
use std::ptr;
// Temporarily turns a mutable reference into an owned value.
fn mut_to_owned<F>(val: &mut MyStruct, f: F)
where
F: FnOnce(MyStruct) -> MyStruct,
{
// We're the only one able to access the data referenced by `val`.
// This operation simply takes ownership of the …Run Code Online (Sandbox Code Playgroud)