rust - 是否可以在不使用 `internal pointers` 的情况下拥有 `Arc` ?

标签 rust

struct Device;

struct CommandBuffer {
    device: &Device,
    // ...
}

// Does not work because Rust does not allow internal pointers
struct Something {
    device: Device,
    command_buffer: CommandBuffer,
}

一个解决方案是使用 Arc

struct CommandBuffer {
    device: Arc<Device>,
    // ...
}
struct Something {
    device: Arc<Device>,
    command_buffer: CommandBuffer,
}

Arc 的缺点是间接性、原子计数器以及逃脱作用域并保持 Device 事件的可能性。

现在我不认为你可以绕过 Rust 中的一个间接级别,但是否有可能在 BoxArc 之间创建一些东西?

struct CommandBuffer {
    device: BoxRef<Device>,
    // ...
}
struct Something {
    device: Box<Device>,
    command_buffer: CommandBuffer,
}

我在尝试实现 BoxRef 时遇到的主要问题是我需要能够移动 Box,即使当前有借用它也是如此。由于间接级别,这在技术上应该是安全的,但我认为目前不能用 Rust 表达。

let boxed_device = Box::new(device);
let device_ref = boxed_device.boxed_ref();

// Owner of the reference should be allowed to move
Something{device: boxed_device, CommandBuffer{device: device_ref}}
  1. BoxRef 可以实现吗?我快速浏览了一下 owning_ref 但它似乎并没有解决我的问题。

  2. 我还有哪些其他选项可以在 Rust 中表达“内部指针”?

最佳答案

这会起作用:

struct Device;

struct CommandBuffer<'a> {
    device: &'a Device, // ...
}

struct Something<'a> {
    device: &'a Device,
    command_buffer: CommandBuffer<'a>,
}

fn main() {

    let dev = Device;

    let smth = Something {
        device: &dev,
        command_buffer: CommandBuffer { device: &dev },
    };
}

你不应该担心 Arc性能那么

通过编写一个保持 Arc 的新类型可以很容易地处理逃逸范围的可能性。私有(private)的,只实现 Deref&T没有Clone .

关于rust - 是否可以在不使用 `internal pointers` 的情况下拥有 `Arc` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39079922/

相关文章:

rust - 无法创建目录时出现 panic

Rust TcpListener 失败但未显示错误

linux - 我应该在 Rust 中的什么地方保存我的配置文件

rust - Rust 的 glob 函数代表什么时间点?

rust - &self 和 self 有什么区别?

rust - 可序列化结构体字段的多种可能类型

macros - 查看 Rust 宏输出

buffer - 在 Rust 中创建字节缓冲区

rust - 如何在 Rust 中实现 HashMap 上带有突变的嵌套循环?

rust - 我得到的特征绑定(bind) `T: sns_pub::_IMPL_DESERIALIZE_FOR_Message::_serde::Serialize` 不满意