提取方法后寿命变小

问题描述 投票:0回答:0

我在 Rust 中提取方法时遇到了一生的问题。以下是一个最小的例子:

pub struct Obj {
    value: usize,
}

pub struct Container<'a> {
    content: &'a Obj,
}

pub struct Props<'a> {
    att: Container<'a>,
}

impl <'a> Props<'a> {
    pub fn value(&self) -> usize {
        self.att.content.value
    }
}

这适用于:

pub fn test<'a>(properties: Props<'a>) -> impl (Fn() -> usize) + 'a {
    || properties.att.content.value
}

但给出错误:

pub fn test<'a>(properties: Props<'a>) -> impl (Fn() -> usize) + 'a {
    || properties.value()
}

closure may outlive the current function, but it borrows 'properties', which is owned by the current function

我想我理解这个错误信息,但我不明白为什么第一段代码编译通过。

properties
在第一个例子中不也是借来的吗?

这个问题可以通过给函数加上一些生命周期来解决吗

value()

Rust 游乐场示例链接

rust lifetime borrow-checker
© www.soinside.com 2019 - 2024. All rights reserved.