I'm using event_emmiter_rs for event handling in my app. This library allows you to subscribe to events with callbacks and also fire those events. Events are in the form of (strings, value) and callbacks are in the form of closures that take in a value parameter. Values sent through the event callbacks must implement Serde::Deserialize. We can see this here in the docs. So I created this simple setup:
use event_emitter_rs::EventEmitter;
use serde::Serialize;
use serde::Deserialize;
use std::borrow::Cow;
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(bound(deserialize = "'de: 'static"))]
//#[serde(bound(deserialize = "'de: 'a"))] using the 'a lifetime gives same error
pub struct DraggableInfo<'a>{
parent: WidgetValue<'a>,
index: WidgetValue<'a>,
draggable_id: WidgetValue<'a>,
}
impl<'a> DraggableInfo<'a>{
pub fn new(parent: &'static str, index: u32, draggable_id: &'static str)->Self{
DraggableInfo{
parent: WidgetValue::CString(Cow::Borrowed(parent)),
index: WidgetValue::Unsized32(index),
draggable_id: WidgetValue::CString(Cow::Borrowed(draggable_id)),
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum WidgetValue<'a>{
Integer32(i32),
Unsized32(u32),
CString(Cow<'a, str>)
}
fn main(){
let mut event_emitter = EventEmitter::new();
event_emitter.on("Print Draggable Value", |dragValue: DraggableInfo| {dbg!(dragValue);});
event_emitter.emit("Print Draggable Value", DraggableInfo::new("root", 0, "layer 1"));
}
But this results in error message:
error: implementation of `Deserialize` is not general enough
--> src\main.rs:34:19
|
34 | event_emitter.on("Print Draggable Value", |dragValue: DraggableInfo| {dbg!(dragValue);});
| ^^ implementation of `Deserialize` is not general enough
|
= note: `DraggableInfo<'_>` must implement `Deserialize<'0>`, for any lifetime `'0`...
= note: ...but `DraggableInfo<'_>` actually implements `Deserialize<'1>`, for some specific lifetime `'1`
I'm not sure what the Deserialize<'0>
and Deserialize<'1>
lifetimes the message refers to are, or exactly what the compiler means when it says the impl is "too general". How might I fix this error?
de: 'static
bound. This means you can only deserialize from static data i.e. data that lives for the entire life of the program. Presumablyevent_emitter
deals with data that is shorter lived than that and that is why it is complaining.#[serde(bound(deserialize = "'de: 'a"))]
gives the same error.Deserialize
for any lifetime.String
instead ofCow<'a, str>
.