首页 > 解决方案 > 从拥有实体和借用实体的功能中移出?

问题描述

这样做的正确方法是什么?有哪些可用选项?我知道悬空引用的问题和自引用结构的问题。我仍然有强烈的直觉,这是一个可以解决的问题,因为所有者和借用的引用都被返回并且没有发生内存释放。也是很普遍的问题!理论上,这是一个可以解决的问题。

use byte_slice_cast::*;

fn main() {
    let context = context_make();
    dbg!(&context);
}

//

fn context_make<'a>() -> Context<'a> {
    Context::<'a>::new()
}

//

#[derive(Debug)]
struct Context<'a> {
    pub dst_buffer: Box<[f32]>,
    pub dst_buffer_bytes: &'a [u8],
}

//

impl<'a> Context<'a> {
    fn new() -> Context<'a> {
        let len: usize = 13;
        let dst_buffer: Box<[f32]> = vec![0_f32; len].into_boxed_slice();
        let dst_buffer_bytes = dst_buffer.as_byte_slice();
        Context {
            dst_buffer,
            dst_buffer_bytes,
        }
    }
}

注意:此代码需要byte-slice-cast = "1.2.0"

如果有不止一种选择,比较解决方案很有趣。

操场

标签: rust

解决方案


我找到了解决方案。它可能在 create 的帮助下owning-ref。有趣的是,在标准 Pin 的帮助下是否可以达到相同的结果?

use byte_slice_cast::*;
use owning_ref::*;

fn main() {
    let context = Context::new();
    dbg!(&context);
    dbg!(context.dst.as_owner());
    dbg!(&*context.dst);
}

//

#[derive(Debug)]
struct Context {
    // pub dst_buffer : Box::< [ f32 ] >,
    // pub dst_buffer_bytes : &'a [ u8 ],
    pub dst: OwningRef<Box<[f32]>, [u8]>,
}

//

impl Context {
    fn new() -> Context {
        let len: usize = 2;
        let dst_buffer: Box<[f32]> = vec![0_f32; len].into_boxed_slice();
        // let dst_buffer_bytes = dst_buffer.as_byte_slice();

        let dst = OwningRef::new(dst_buffer);
        let dst = dst.map(|dst_buffer| dst_buffer.as_byte_slice());

        Context { dst }
        // Context { dst_buffer, dst_buffer_bytes }
    }
}

操场


推荐阅读