小编Gym*_*ore的帖子

有没有办法告诉 Rust 的 drop checker 我们有效地拥有一个 `T` 而不是它在通用参数中?

假设我想写这样的代码:

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 编译器允许我这样做,只要我不DropInspector.

如果我添加一个,则会出现以下编译时错误:

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)

lifetime rust borrow-checker

6
推荐指数
1
解决办法
121
查看次数

有没有一种安全的方法可以从 Rust 的可变引用中临时检索一个拥有的值?

我正在使用两个独立的功能。

  • 第一个获取结构的拥有实例,然后返回它。
  • 第二个采用可变引用但需要使用第一个函数。
// 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)

unsafe ownership rust

3
推荐指数
1
解决办法
63
查看次数

标签 统计

rust ×2

borrow-checker ×1

lifetime ×1

ownership ×1

unsafe ×1