Suppose you have a Writer<T>
struct as follows:
struct Writer<T> {
m: std::marker::PhantomData<fn(&T)>,
}
impl<T> Writer<T> {
fn write(&mut self, val: &T) {} // somehow knows what to do - that's not important
}
The Writer
is generic only to associate the T
with the method parameter in write()
- it otherwise doesn't store or use the T
.
Next, you have a struct like this:
struct Record<'a> {
x: &'a i32,
}
And now you want to have a Logger
struct as follows:
// Don't want a lifetime parameter on `Logger`
struct Logger {
rec_writer: Writer<Record<'static>>, // it's not really 'static
}
impl Logger {
fn write_record(&mut self) {
let x = 5;
let rec = Record {x: &x};
let rec: Record<'static> = unsafe {
std::mem::transmute(rec)
};
self.rec_writer.write(&rec);
}
}
So here I'm transmuting to 'static
to satisfy the type system, and I know that rec_writer.write(...)
will not attempt to stash any values out of Record
on the premise that they're 'static
(which they're not). Ideally, what I'd like to express is:
struct Logger {
rec_writer: for<'a> Writer<Record<'a>>,
}
which of course is invalid since HRTB only works on traits.
Is there a clean way to achieve this? Am I forgetting something? I can probably redesign the code to not be structured like this, but I'm curious if this is feasible as-is.