Does not compile: wasm32, local storage, bindecode

    pub fn storage_get<'a, T: serde::Deserialize<'a>>(name: &str) -> Option<T> {
        let storage = stdweb::web::window().local_storage();
        let x = storage.get(name)?;
        let y = base64::decode(&x).ok()?;
        let z = bincode::deserialize::<T>(&y).ok()?;
        Some(z)
    }

Error is:

11 |     pub fn storage_get<'a, T: serde::Deserialize<'a>>(name: &str) -> Option<T> {
   |                        -- lifetime `'a` defined here
...
15 |         let z = bincode::deserialize::<T>(&y).ok()?;
   |                 --------------------------^^-
   |                 |                         |
   |                 |                         borrowed value does not live long enough
   |                 argument requires that `y` is borrowed for `'a`
16 |         Some(z)
17 |     }
   |     - `y` dropped here while still borrowed

What am I doing wrong?

You're deserializing a T from &y and the T: Deserialize<'a> bound says your T will live for the lifetime 'a, which means T can't outlive y. rustc is complaining because once the function returns y will be destroyed and the T will be (possibly) referencing garbage data.

Instead of T: Deserialize<'a> which says the T may contain pointers into the data it was deserialized from, you should write T: serde::de::DeserializeOwned which will make sure the T type owns all the data it contains.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.