rust - 从拥有实体和借用实体的功能中移出?
问题描述
这样做的正确方法是什么?有哪些可用选项?我知道悬空引用的问题和自引用结构的问题。我仍然有强烈的直觉,这是一个可以解决的问题,因为所有者和借用的引用都被返回并且没有发生内存释放。也是很普遍的问题!理论上,这是一个可以解决的问题。
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"
如果有不止一种选择,比较解决方案很有趣。
解决方案
我找到了解决方案。它可能在 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 }
}
}
推荐阅读
- python - 全局变量显示为局部变量
- python - 我的脚本没有在循环中创建类的实例 [python]
- arrays - 如何构建一个 numpy 对象数组(对象包含另一个数组)
- typescript - 使用 Jasmine 监视私有变量的属性/函数
- google-secret-manager - Google Secret Manager - 可以用于存储 API 用户的用户名和密码吗?
- android - 如何在 Embarcadero RAD Studio 10.3.3 中调试 android 64 位应用程序成为可能?
- python - 如何创建一个也使用 PyGame 库的可执行 (.exe) Python 程序
- php - 关闭选项卡后会话正在破坏 - 社交名流 Laravel
- f# - 在 F# 中扩展函数
- python - 如何访问作为另一个类中方法的输入的变量?