Right way to mark lifetime in an `impl`

struct Foo<'a>{
    a:Option<&'a i32>,
}
struct Bar{}

impl Bar{
    async fn print(&self,arg:&mut Foo) {
    }
}


fn main()
{
    let mut a = 100;
    let mut z = Foo{a:Some(&a)};
    let b = Bar{};
    b.print(&mut z);
    
    
}

Getting below error for the above code

   Compiling playground v0.0.1 (/playground)
error[E0726]: implicit elided lifetime not allowed here
  --> src/main.rs:11:35
   |
11 |     async fn print(&self,arg:&mut Foo) {
   |                                   ^^^- help: indicate the anonymous lifetime: `<'_>`
   |
   = note: assuming a `'static` lifetime...

error: could not compile `playground` due to previous error

here where should i place 'a in impl?

The compiler suggests

impl Bar{
    async fn print(&self,arg:&mut Foo<'_>) {
    }
}

which does compile successfully.

2 Likes

Also, the async keyword on that function is preventing the code you posted from doing anything useful— You'll need to set up an executor (like tokio) and call print().await before it will actually do any work. Or you can drop the async keyword.

1 Like

thanks!! i have totally missed it . i was aware of static & named lifetimes but not anonymous lifetime . is it mentioned in the rust book ?

I don’t know. It might not be mentioned. I couldn’t find it on a quick search. It does appear in the nomicon at least once

Lifetime Elision - The Rustonomicon

and more properly in the reference

Lifetime elision - The Rust Reference