Closed
Description
The following piece of code does not compile:
pub struct Callbacks {
callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
}
impl Callbacks {
pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
self.callbacks.push(Rc::new(RefCell::new(callback)));
}
}
(Playpen)
However, an explicit type annotation makes the code compile just fine:
use std::rc::Rc;
use std::cell::RefCell;
pub struct Callbacks {
callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
}
impl Callbacks {
pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
self.callbacks.push(Rc::new(RefCell::new(callback)) as Rc<RefCell<F>>);
}
}
Alternatively, one can introduce an intermediate variable for the argument of push
. Then Rust is fine with not having an annotation.
Rust should infer the proper types automatically, to make this annotation unnecessary even without an intermediate variable.
This is with current beta and nightly. (Stable does not support the unsized stuff well enough to write this at all.)