Closed
Description
This code works:
fn main() {
let func: Box<Fn()> = Box::new(|| println!("called"));
func();
}
As does placing it in an array:
fn main() {
let func: [Box<Fn()>; 1] = [Box::new(|| println!("called"))];
func[0]();
}
However, using a Vec
fails:
fn main() {
let func: Vec<Box<Fn()>> = vec![Box::new(|| println!("called"))];
func[0](); // error: expected function, found `Box<std::ops::Fn()>`
}
Instead, it must be explicitly dereferenced:
fn main() {
let func: Vec<Box<Fn()>> = vec![Box::new(|| println!("called"))];
(*func[0])();
}
It's even more annoying for Vec<Box<FnMut()>>
:
fn main() {
let mut func: Vec<Box<FnMut()>> = vec![Box::new(|| println!("called"))];
// func[0](); // expected function, found `Box<std::ops::FnMut()>`
// (*func[0])(); // cannot borrow immutable `Box` content as mutable
(*&mut func[0])();
}
Metadata
Metadata
Assignees
Labels
No labels