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

1

8

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
Lakendra answered 5/9, 2019 at 2:23 Comment(1)
Possible duplicate of Lifetimes when Deserializing JSON within a FromFormHumphreys
L
13
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),
    }
}
Lakendra answered 5/9, 2019 at 8:20 Comment(1)
DeserializeOwned just solved 3 hours of Box workarounds, thanks 👍🏼Hanleigh

© 2022 - 2024 — McMap. All rights reserved.