2
votes

borrowed value does not live long enough when use generic lifecycle。

fn get<'a, T>(&self, key: &[u8]) -> Result<Option<T>>
where
    T: Deserialize<'a>,
{
    match self.db.get(key)? {
        Some(dbv) => {
            let v = serde_json::from_slice(&*dbv)?;
            Ok(Some(v))
        }
        None => Ok(None),
    }
}

funcion db.get declaration:

pub fn get(&self, key: &[u8]) -> Result<Option<DBVector>, String>

function serde_json::from_slice declaration:

pub fn from_slice<'a, T>(v: &'a [u8]) -> Result<T>
where
    T: de::Deserialize<'a>

the error message:

error[E0597]: `dbv` does not live long enough
   --> libs/block-db/src/index.rs:106:50
    |
100 |     fn get<'a, T>(&self, key: &[u8]) -> Result<Option<T>>
    |            -- lifetime `'a` defined here
...
106 |                 let v = serde_json::from_slice(&*dbv)?;
    |                         -------------------------^^^-
    |                         |                        |
    |                         |                        borrowed value does not live long enough
    |                         argument requires that `dbv` is borrowed for `'a`
...
109 |             None => Ok(None),
    |                - `dbv` dropped here while still borrowed

error: aborting due to previous erro
1

1 Answers

0
votes
fn get<T>(&self, key: &[u8]) -> Result<Option<T>>
where
    T: DeserializeOwned,
{
    match self.db.get(key)? {
        Some(ref dbv) => {
            let v = serde_json::from_slice(dbv)?;
            Ok(Some(v))
        }
        None => Ok(None),
    }
}