Sequential Execution of Functions


#1

I am trying to get a list of functions to sequentially be applied to a mutable object in a user-configurable way, but I keep getting an error that suggests that the functions themselves need to be mutable in order for this to work. Here’s a minimal example that won’t compile:

type StackOperation = Box<FnMut(&mut Vec<i32>) -> bool>;

fn composite_op(parts: Vec<StackOperation>) -> StackOperation {
    Box::new(move |mut x| {
        for op in &parts {
            if !op(&mut x) {
                return false;
            }
        }
        true
    })
}

The compiler tells me “error: cannot borrow immutable Box content **op as mutable” on the line if !op(&mut x) {.

What am I missing here?


#2

Parts should be mut. To call a FnMut one must have a mut value.

fn composite_op(mut parts: Vec<StackOperation>) -> StackOperation {
    Box::new(move |mut x| {
        for op in &mut parts {
            if !op(&mut x) {
                return false;
            }
        }
        true
    })
}