尝试创建一个返回反序列化值的常规函数

时间:2017-11-03 02:22:10

标签: rust serde

我正试图概括这个功能:

fn test() -> MyStruct {
    let u: [u8; 5] = [1, 2, 3, 4, 5];
    let deserialized_struct: MyStruct = serde_json::from_slice(&u).unwrap();
    deserialized_struct
}

我创建了:

fn test<'a, T>() -> T
    where T: serde::Deserialize<'a>
{
    let u: [u8; 5] = [1, 2, 3, 4 ,5];
    let deserialized_struct: T = serde_json::from_slice(&u).unwrap();
    deserialized_struct
}

失败了:

error[E0597]: `u` does not live long enough
  --> src/main.rs:9:58
   |
9  |     let deserialized_struct: T = serde_json::from_slice(&u).unwrap();
   |                                                          ^ does not live long enough
10 |     deserialized_struct
11 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 4:1...
  --> src/main.rs:4:1
   |
4  | / fn test<'a, T>() -> T
5  | | where
6  | |     T: serde::Deserialize<'a>,
7  | | {
...  |
10 | |     deserialized_struct
11 | | }
   | |_^

0 个答案:

没有答案