1

我试图概括这个功能:

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 | | }
   | |_^
4

0 回答 0