I'm having issues with storing a type on a struct using PhantomData. In the PhantomData docs (PhantomData in std::marker - Rust), it suggests using PhantomData<*const T>
when the compiler doesn't have to worry about lifetimes - but it still seems to be an issue.
Is it possible to achieve this without Rust thinking I'm trying to smuggle data out of a closure?
struct Logger<M> {
__message_type: std::marker::PhantomData<*const M>
}
impl<M: std::fmt::Debug> Logger<M> {
fn log(&mut self, message: &M) {
println!("{:?}", message);
}
}
#[derive(Debug)]
struct Message<'a> {
caller: String,
error: &'a String
}
fn create_error<F: FnMut(&String)>(mut func: F) {
let s = String::from("Hello");
func(&s)
}
fn main() {
let mut logger = Logger { __message_type: Default::default() };
create_error(|error| {
let message = Message {
caller: "Me".into(),
error
};
logger.log(&message);
});
}
Errors:
Compiling playground v0.0.1 (/playground)
error: borrowed data cannot be stored outside of its closure
--> src/main.rs:29:13
|
23 | let mut logger = Logger { __message_type: Default::default() };
| ---------- ...so that variable is valid at time of its declaration
24 |
25 | create_error(|error| {
| ------- borrowed data cannot outlive this closure
26 |
27 | let message = Message {
| ------- cannot infer an appropriate lifetime...
28 | caller: "Me".into(),
29 | error
| ^^^^^ cannot be stored outside of its closure
error: aborting due to previous error
error: could not compile `playground`.
To learn more, run the command again with --verbose.