【问题标题】:How do I enforce parent-child struct lifetime?如何强制执行父子结构生命周期?
【发布时间】:2015-12-02 08:37:23
【问题描述】:

我正在为外部 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();
}

【问题讨论】:

  • 我认为您出于某种原因不想继续在Child 中添加对Parent 的引用?

标签: rust


【解决方案1】:

PhantomData 的想法是正确的。您将生命周期参数和PhantomData 字段添加到ChildPhantomData 泛型参数是您要在结构中模拟的内容。在这种情况下,您希望 Child 就像它包含 &Parent 一样。

struct Child<'a> {
    parent: PhantomData<&'a Parent>,
}

impl Parent {
    fn get_child<'a>(&'a self) -> Child<'a> {
        Child {
            parent: PhantomData,
        }
    }
}

您还需要修改test 函数以具有通用参数,否则您看不到您请求的doesn't live long enough 错误, 因为首先出现Child needs a lifetime错误。

fn test<'a>() -> Child<'a> {
    let p = Parent;
    p.get_child()
}

Try it out in the Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多