Search code examples
rustactix-web

actix web lifetime in web::Data


I am trying to work with Data in acitx web, but it wont work with a defined lifetime. Why am i getting this error and how do i fix it? implicit elided lifetime not allowed here assuming a 'static lifetime

#[get("/search/{query}/")]
async fn testing(search: Path<SearchIdentifier>,test: Data< Test >) -> Json<String> {...} 
error[E0726]: implicit elided lifetime not allowed here
  --> src/api/file.rs:86:62
   |
86 | async fn testing(search: Path<SearchIdentifier>,test: Data< Test >) -> Json<String> {
   |                                                            ^^^^^^- help: indicate the anonymous lifetime: `<'_>`
   |
   = note: assuming a `'static` lifetime...
pub struct Test<'a> {
    test: Test<'a>,
}

impl<'a> Test<'a> {
    pub fn new(conn: MysqlConnection) -> Self {
        let test = Test { conn: &conn };
        Self {test}
    }

Solution

  • Test contains a lifetime - 'a. You omitted it. Usually, when you do that, the compiler uses the lifetime elision rules to figure out what the lifetime should be - in this case, for example, it would become:

    fn testing<'a>(search: Path<SearchIdentifier>,test: Data<Test<'a>>) -> Json<String>
    

    However, this is not a normal function. This is an async function. And async functions are not allowed to implicitly elide the lifetime - they have to explicitly elide it using '_, that is:

    async fn testing(search: Path<SearchIdentifier>,test: Data<Test<'_>>) -> Json<String>
    

    Or, of course, the fully-specified version with 'a.

    The reason for that is that implicit lifetime elision on structs is considered a design mistake, because it does not allow you to reason easily about the lifetimes present in your function. In fact, I recommend putting at the crate root the following:

    #![forbid(rust_2018_idioms)]
    

    To (among other things) disallow that for any function, not just async.