Rust 如何强制父子结构生命周期?
我正在为一个外部C库编写包装器代码,并试图说服Rust编译器强制执行外部生存期限制,这些限制不会反映在Rust代码本身中。例如,一种类型的“不透明句柄”可以返回仅在父句柄的生存期内有效的子句柄 我尝试了Rust 如何强制父子结构生命周期?,rust,Rust,我正在为一个外部C库编写包装器代码,并试图说服Rust编译器强制执行外部生存期限制,这些限制不会反映在Rust代码本身中。例如,一种类型的“不透明句柄”可以返回仅在父句柄的生存期内有效的子句柄 我尝试了std::marker::PhantomData,但我无法说服编译器返回预期的错误 换句话说,我希望以下代码块无法编译: struct Parent; struct Child; // Note that there is no reference to the parent struct i
std::marker::PhantomData
,但我无法说服编译器返回预期的错误
换句话说,我希望以下代码块无法编译:
struct Parent;
struct Child; // Note that there is no reference to the parent struct
impl Parent {
fn get_child( &self ) -> Child {
Child
}
}
// I'd like this to complain with "p does not live long enough"
fn test() -> Child {
let p = Parent;
p.get_child()
}
fn main() {
let c = test();
}
您对幻影数据的想法是正确的。将生存期参数和
PhantomData
字段添加到Child
。PhantomData
generic参数是要在结构中模拟的参数。在这种情况下,您希望子项
的行为就像它包含一个&父项
struct Child<'a> {
parent: PhantomData<&'a Parent>,
}
impl Parent {
fn get_child<'a>(&'a self) -> Child<'a> {
Child {
parent: PhantomData,
}
}
}
我假设您不想在
子项中添加对父项的引用是有原因的?
fn test<'a>() -> Child<'a> {
let p = Parent;
p.get_child()
}