Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async-trait cannot handle trait<'a>? #28

Closed
UkonnRa opened this issue Sep 16, 2019 · 1 comment · Fixed by #30
Closed

async-trait cannot handle trait<'a>? #28

UkonnRa opened this issue Sep 16, 2019 · 1 comment · Fixed by #30
Labels
bug Something isn't working

Comments

@UkonnRa
Copy link

UkonnRa commented Sep 16, 2019

I want to write a trait with lifetime, say:

use async_trait::async_trait;
use futures::executor::block_on;
pub struct Something<'a> {
    name: &'a str,
}

#[async_trait]
pub trait Abstract<'a> {
    async fn hello(thing: Something<'a>) -> String;
    async fn hello_ref(thing: Something<'a>) -> &'a str;
}

pub struct Real();
#[async_trait]
impl <'a> Abstract<'a> for Real {
    async fn hello(thing: Something<'a>) -> String {
        String::from(thing.name)
    }

    async fn hello_ref(thing: Something<'a>) -> &'a str {
        thing.name
    }
}

fn main() {
    let thing = Something{ name: "name" };
    let name = block_on(Real::hello(thing));
    println!("name: {}", name);
}

But it will throw an Error:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
  --> src\main.rs:14:1
   |
14 | #[async_trait]
   | ^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 15:7...
  --> src\main.rs:15:7
   |
15 | impl <'a> Abstract<'a> for Real {
   |       ^^
   = note: ...so that the expression is assignable:
           expected Something<'_>
              found Something<'a>
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected std::pin::Pin<std::boxed::Box<(dyn core::future::future::Future<Output = std::string::String> + std::marker::Send + 'static)>>
              found std::pin::Pin<std::boxed::Box<dyn core::future::future::Future<Output = std::string::String> + std::marker::Send>>

I wonder am I do anything wrong? How to set the lifetime correctly?

@UkonnRa
Copy link
Author

UkonnRa commented Sep 16, 2019

Works! THX!

@dtolnay dtolnay added the bug Something isn't working label Oct 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants