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
Assignees
Labels
No labels
Activity
Aatch commentedon Sep 29, 2016
The fact that this works for arrays, but not Vec suggests that it's probably related to associated types. It's possible that wherever the coercion from
&Box<Fn()>
to&Fn()
is done sees&<Vec<Box<Fn()>> as Index<usize>>::Output
instead.Resolve the callee type in check_call before autoderef
Auto merge of #36822 - Aatch:resolve-callee-expr, r=luqmana
Resolve the callee type in check_call before autoderef
jonhoo commentedon Mar 7, 2017
This doesn't seem to be fully resolved:
shepmaster commentedon Nov 12, 2017
@jonhoo That may be #26186 instead.