Does not live enough error

Hi people,

I am using actix web and i have a borrowing compile error.
Do you have any idea of what is going wrong?

Thank you~

use actix_web::web;
use serde::Deserialize;

use std::str;

#[derive(Debug, Deserialize, Clone)]
pub struct Params {
    q: String,

pub fn parse<'a, T>(query: &'a str) -> Result<T, std::io::Error>
    T: Deserialize<'a>,
    let params = web::Query::<Params>::from_query(query).unwrap();

    let base64_buf = base64::decode(&params.q).unwrap();

    let to_string = str::from_utf8(&base64_buf).unwrap();  // ERROR => base64_buf does not live enough borrowed value does not live long enough

    let file_ref: T = serde_json::from_str(to_string).unwrap();


The issue is indeed with base64_buf.
The thing is, that buffer is created as a function-local binding, and since it isn't moved it is dropped when the fn returns.

The other aspect of this is T: Deserialize<'a>. Using that bound means that the deserialized value borrows from the query fn parameter.
For more info on why, you can read this.
What you may want instead in this case is to use T: DeserializeOwned, as that decouples the lifetime of the deserialized value from the lifetime of the query parameter. That in turn would allow you to return the deserialized value without issues.


Thanks @jjpe !
It works well just by changing as you said T: Deserialize<'a>, by T: DeserializeOwned,.
Thanks for your help again.