Skip to content

Cannot call a Vec<Box<Fn()>> without explicit dereferencing #36786

Closed
@shepmaster

Description

@shepmaster

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions