cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements for struct made of enums with Serde Deserialize

Viewed 323

Why can I auto derive serde::Deserializefor my WidgetValue enum, but not for a struct made up entirely of WidgetValue fields?

This seems counterintuitive to me.

EDIT: For various reasons, I'm using the WidgetValue enum because I'd like to send different values through a function with the same type signature. See Vector store mixed types of data in Rust, How do I create a heterogeneous collection of objects?, etc.

serde = { version = "1.0.126", features = ["derive"] }
//works fine
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum WidgetValue{
    Integer32(i32),
    Unsized32(u32),
    CString(&'static str),
}

//lifetime error
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct DraggableInfo{
    parent: WidgetValue,
    index: WidgetValue,
    draggable_id: WidgetValue,
}

Error:

cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
1 Answers

You can fix the lifetime error, by manually providing a bound on the 'de lifetime during deserialization. Due to the &'static str the enum WidgetValue only implements Deserialize<'static> since no other lifetime works to borrow a &'static str. This leads to an error for DraggableInfo since by default the 'de lifetime is not constrained. With this manual bound you declare 'de to outlive 'static, making them equal.

#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
#[serde(bound(deserialize = "'de: 'static"))]
pub struct DraggableInfo{
    parent: WidgetValue,
    index: WidgetValue,
    draggable_id: WidgetValue,
}

#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum WidgetValue{
    Integer32(i32),
    Unsized32(u32),
    CString(&'static str),
}

You likely do not want to use it like this though, since you can only derive from 'static data. You can redefine CString like this CString(Cow<'static, str>) to allow both static string literals and deserializing from non-static data.

Related