我正在为外部C库编写包装器代码,并且我试图说服Rust编译器强制执行外部生命周期限制,这些限制未反映在Rust代码本身中.例如,一种类型的"不透明句柄"可以返回仅在父句柄的生命周期内有效的子句柄.
我试验过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();
}
Run Code Online (Sandbox Code Playgroud)
你有正确的想法PhantomData.您可以添加生命周期参数和PhantomData字段Child.该PhantomData泛型参数是要在结构来效仿.在这种情况下,您希望表现Child得好像它包含一个&Parent.
struct Child<'a> {
parent: PhantomData<&'a Parent>,
}
impl Parent {
fn get_child<'a>(&'a self) -> Child<'a> {
Child {
parent: PhantomData,
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还需要修改test函数以具有泛型参数,否则您不会看到所请求的doesn't live long enough错误,因为Child needs a lifetime错误首先发生.
fn test<'a>() -> Child<'a> {
let p = Parent;
p.get_child()
}
Run Code Online (Sandbox Code Playgroud)