I am having trouble to understand how i return types like CallbackGuard(devicequery::DeviceEvents). I tryed to create a function that listen to keyboard and prints it. But when i call this function, the closure inside device_state.on_key_up (i believe) dies and nothing is printed.
fn main() {
let device_state = listen_to();
loop {}}
fn listen_to() -> DeviceState<>{
let device_state = DeviceState::new();
let keys = device_state.on_key_up(|key|{
println!("{:#?}", key);});
return keys;}
So i tryed to return it, thinking that this wouldnt happen. But now im facing a problem with the return type of the function. Someone can give me a light on this?
Edit:
I know that i am not returning the right type, what i dont understand is what is the right type to return in this kind of situation. Can i return keys in this case?
For those who will have the same doubt, i found the answer.
fn main() {
let device_state: DeviceState = DeviceState::new();
let device_state = listen_to(device_state);
loop{}
}
fn listen_to(device_state:DeviceState) -> CallbackGuard<impl Fn(&Keycode)>
{
device_state.on_key_down(|keys|{
println!("Keys: {}", keys)})
}
The main problem was understanding how to return a scope from a struct's method. The key to the answer was understand how impl and Fn works. In this case, the <impl Fn(&Keycode)>
is saying to the compiler that within CallbackGuard
will be a function that takes a &Keycode
argument and returns a closure.