The root of this question is: How do I return a value borrowed within function?
I am trying to write a helper function which gets a value from Redis, deserializes it using Serde JSON, and returns the value.
The problem is Serde's deserialization lifetime, which enforces that the data being deserialized must live as long as the resulting deserialized value.
My issue is that I retrieve the data being deserialized within the helper function. So the borrow of this data can never last longer than the lifetime of the function. However the resulting deserialized data will last longer than the function.
How do I make this helper function work? My intitution makes me think I need to do some sort of clone, copy, or move on the returned data.
Example:
use serde::Deserialize;
use serde_json;
use redis::aio::MultiplexedConnection;
/// Retreive an item represented in Redis as JSON.
async fn load_from_redis<'a, T: Deserialize<'a>>(
redis_conn: &'a mut MultiplexedConnection,
key: &'a str
) -> Result<T, String>
{
let data_json: String = match redis_conn.get(key).await {
Err(e) => return Err(format!("Failed to get data from Redis: {}", e)),
Ok(v) => v,
};
match serde_json::from_str(data_json.as_str()) {
Err(e) => Err(format!("Failed to deserialize data: {}", e)),
Ok(v) => Ok(v),
}
}
Which results in the error:
error[E0597]: `data_json` does not live long enough
--> src/main.rs:49:32
|
39 | async fn load_from_redis<'a, T: Deserialize<'a> + Copy + std::clone::Clone>(
| -- lifetime `'a` defined here
...
49 | match serde_json::from_str(data_json.as_str()) {
| ---------------------^^^^^^^^^----------
| | |
| | borrowed value does not live long enough
| argument requires that `data_json` is borrowed for `'a`
...
53 | }
| - `data_json` dropped here while still borrowed