基于您的要求的结构的原始设计可能如下所示:
struct AnotherObj<'a> {
original: &'a Vec<i8>, // Let's agree on Vec<i8> as your "data" type.
}
struct Obj<'a> {
original: Vec<i8>, // <-------------------+
processed: AnotherObj<'a>, // should point here --+
}
但是开始工作非常棘手(就我个人而言,我做不到),因为您希望AnotherObj<'a> 中的'a 成为original 的生命周期。但是,您必须为Obj<'a> 提供生命周期,因此您必须指定Obj<'tbc>,其中'tbc 是要创建的Obj 的生命周期。
我建议以下替代方案:
1。让AnotherObj真正拥有原来的
为什么不呢? Obj 将拥有AnotherObj,因此它仍然可以作为嵌套子级访问original:
pub struct AnotherObj {
original: Vec<i8>,
}
pub struct Obj {
processed: AnotherObj,
}
pub fn new() -> Obj {
let data = vec![1,2,3];
Obj {
processed: AnotherObj {
original: data,
// ...
}
}
}
// access as obj.processed.original, you can even create a getter `fn original(&self)`
2。共享指针设计
引用计数指针的直接使用:
use std::rc::Rc;
pub struct AnotherObj {
original: Rc<Vec<i8>>,
}
pub struct Obj {
original: Rc<Vec<i8>>,
processed: AnotherObj,
}
pub fn new() -> Obj {
let data = Rc::new(vec![1,2,3]);
Obj {
original: data.clone(),
processed: AnotherObj {
original: data.clone(),
}
}
}
3。使用原始指针
选项 1. 和 2. 会给你带来安全的 Rust 之神般的安心,因此我不推荐第三种选择。为了完整起见,我仍然在这里发布。注意:它可以编译,但我从未在运行时测试过它,所以它可能会咬人。下面只有安全代码,但当您想取消引用原始指针时,您必须进入unsafe 土地。
use std::ptr;
pub struct AnotherObj {
original: *mut Vec<i8>,
}
pub struct Obj {
original: Vec<i8>,
processed: AnotherObj,
}
pub fn new() -> Obj {
let data = vec![1,2,3];
let mut obj = Obj {
original: data,
processed: AnotherObj {
original: ptr::null_mut(),
}
};
obj.processed.original = &mut obj.original as *mut Vec<i8>;
obj
}