使用通用生命周期时,借入的价值不能长期使用。

时间:2019-09-05 02:23:33

标签: rust lifetime serde-json

使用通用生命周期时,借入的价值不能长期使用。

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),
    }
}

功能db.get声明:

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

函数serde_json :: from_slice声明:

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

错误消息:

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 个答案:

答案 0 :(得分:-1)

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),
    }
}