我如何 return 从闭包中引用闭包的参数?

How do I return a reference to a closure's argument from the closure?

我是 Rust 新手,对生命周期省略和推理的所有规则都不了解。我似乎无法从闭包中返回对参数的引用来工作,而且这些错误对以我的知识量的人来说帮助不大。

我可以使用带有生命周期注释的适当函数来代替闭包,但无法找到在闭包上注释这些生命周期的方法。

struct Person<'a> {
    name: &'a str,
}

impl<'a> Person<'a> {
    fn map<F, T>(&'a self, closure: F) -> T
        where F: Fn(&'a Person) -> T
    {
        closure(self)
    }
}

fn get_name<'a>(person: &'a Person) -> &'a str {
    person.name
}

fn main() {
    let p = Person { name: "hello" };
    let s: &str = p.map(|person| person.name); // Does not work
    // let s: &str = p.map(get_name);  // Works
    println!("{:?}", s);
}

这是编译器错误:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:19:34
   |
19 |     let s: &str = p.map(|person| person.name); // Does not work
   |                                  ^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 19:33...
  --> src/main.rs:19:34
   |
19 |     let s: &str = p.map(|person| person.name); // Does not work
   |                                  ^^^^^^^^^^^
note: ...so that expression is assignable (expected &str, found &str)
  --> src/main.rs:19:34
   |
19 |     let s: &str = p.map(|person| person.name); // Does not work
   |                                  ^^^^^^^^^^^
note: but, the lifetime must be valid for the method call at 19:18...
  --> src/main.rs:19:19
   |
19 |     let s: &str = p.map(|person| person.name); // Does not work
   |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that pointer is not dereferenced outside its lifetime
  --> src/main.rs:19:19
   |
19 |     let s: &str = p.map(|person| person.name); // Does not work
   |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^

这里发生了什么,如何更改闭包使其工作?

我认为我混淆了对 Person 的引用的生命周期与结构(&str 引用的)的生命周期参数。编译:

struct Person<'a> {
    name: &'a str,
}

impl<'a> Person<'a> {
    fn map<F, T>(&self, closure: F) -> T
        where F: Fn(&Person<'a>) -> T
    {
        closure(self)
    }
}

fn get_name<'a>(person: &Person<'a>) -> &'a str {
    person.name
}

fn main() {
    let p = Person { name: "hello" };
    println!("{:?}", p.map(|person| person.name));
    println!("{:?}", p.map(get_name));
}

我不确定我对生命周期注解的理解是否正确,也许其他人可以把上面的编译错误挑出来。语言极其混乱。