Hi,
I'm trying to setup lifetimes such as that the user can't send in some data that doesn't outlive the handler
in this case.
This code bellow works as intended but I have some questions regarding it (see under the code)
//#![feature(nll)]
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::mem::transmute;
struct Handler<'a> {
_marker: PhantomData<&'a u32>,
}
impl<'a> Handler<'a> {
pub fn on_change<T>(&mut self, data: &'a mut T)
where T: 'a,
{
unsafe {
let user_data: *const c_void = transmute(data);
println!("{:?}", user_data)
}
}
}
fn main() {
//let mut foo = 1; // this line should be valid
let mut handler = Handler { _marker: PhantomData };
let mut foo = 1; // this line should be illegal
handler.on_change(&mut foo);
}
1:
if I change:
pub fn on_change<T>(&mut self, data: &'a mut T)
to
pub fn on_change<T>(&self, data: &'a mut T)
It doesn't prevent the local variable to be sent in. Why is that?
2:
Also if I enable NLL on nightly it also doesn't work (user can send in the variable without any compilation error) Wondering if my code is wrong or that this is an issue with NLL?
3:
I also would like to support doing
handler.on_change(&mut foo);
handler.on_change(&mut foo);
But the compiler will complain that it's already borrowed. I figured it would only be borrowed when sent to the function and then be allowed to be re-borrowed when it comes back (adding scopes around it doesn't help either)
Thanks!