基于需求的 struct 的原始设计可能如下所示:
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. Make AnotherObj actually own the original
为什么不呢?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.共享指针设计
直接使用refcounted指针:
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 神的宁静,因此我不推荐第三种 Select .为了完整起见,我还是把它贴在这里.注意:它可以编译,但我从未在运行时测试过,所以它可能会有用.下面只有安全代码,但是当你想要取消对原始指针的引用时,你必须进入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
}