I have the following rust code cannot be compiled.
struct Person { name : String, age : u8, } fn main() { let p = Person{ name: "Nobody".to_string(), age : 24}; let age = |p : &Person| p.age; let name = |p : &Person | &p.name; println! ("name={}, age={}" , name(&p), age(&p)); } And the compiler gave the following error message.
Compiling playground v0.0.1 (/playground) error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements --> src/main.rs:11:31 | 11 | let name = |p : &Person | &p.name; | ^^^^^^^ | note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 11:16... --> src/main.rs:11:16 | 11 | let name = |p : &Person | &p.name; | ^^^^^^^^^^^^^^^^^^^^^^ note: ...so that reference does not outlive borrowed content --> src/main.rs:11:31 | 11 | let name = |p : &Person | &p.name; | ^^^^^^^ note: but, the lifetime must be valid for the expression at 2:29... --> src/main.rs:13:5 | 13 | println! ("name={}, age={}" , name(&p), age(&p)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...so type `(&&std::string::String, &u8)` of expression is valid during the expression --> src/main.rs:13:5 | 13 | println! ("name={}, age={}" , name(&p), age(&p)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) error: aborting due to previous error I tried to add the lifetime for name closure.
let name<'a> = |p : &'a Person | -> &'a String { &'a p.name }; but still got the compiler error
Compiling playground v0.0.1 (/playground) error: expected one of `:`, `;`, `=`, `@`, or `|`, found `<` --> src/main.rs:12:13 | 12 | let name<'a> = |p : &'a Person | -> &'a String { &'a p.name }; | ^ expected one of `:`, `;`, `=`, `@`, or `|` error: aborting due to previous error Just want to know how to write the correct code.