Hi forum, first time poster here.
Say I have a Notify
trait:
trait Notify {
type Message;
type Error;
fn notify(&self, message: Self::Message) -> Result<(), Self::Error>;
}
and a Notifier
type that provides generic implementation for anything that is Serialize
:
struct Notifier<M>(__phantom: PhantomData<fn(M)>);
impl<M: Serialize> Notify for Notifier<M> {
type Message = M;
type Error = SomeErrorType;
fn notify(&self, message: Self::Message) -> Result<(), Self::Error> {
/* implementation... */
}
}
I want to define a concrete type EmailNotifier
that accepts the email body as string, and sends it by delegating to the generic implementation:
#[derive(Serialize)]
struct EmailPayload<'a> {
sender: &'a str,
receiver: &'a str,
message: String,
}
struct EmailNotifier<'a> {
sender: String,
receiver: String,
notifier: Notifier<EmailPayload<'a>>
};
impl<'a> Notify for EmailNotifier<'a> {
type Message = String;
type Error = SomeErrorType;
fn notify(&self, message: Self::Message) -> Result<(), Self:: Error> {
let payload = EmailPayload {
sender: &self.sender,
receiver: &self.receiver,
message,
};
self.notifier.notify(payload)
}
}
This code works, but as you can see the type carries a lifetime type parameter 'a
, which is strictly shorter than the borrow of self. Can I convey this information to the compiler so that EmailNotifier
does not need to carry this lifetime parameter, as it leaks internal implementation details?
Thank you for taking time to read through the post, any help is appreciated.
EDIT: also assume the error type is 'static
so it does not use borrows from the payload.