Understanding a borrow checker error: moving the results of a borrowed function

⚓ Rust    📅 2025-06-24    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 49 days ago. The information described in this article may have changed.

Hello,

I am unsure whether I understand the reason for this borrow checker error.
The problem is moving the result of f(pop1.unwrap(), op2) into the push() method correct?
But why is this apparently caused because f is a reference?

    /// applies a binary operator (+,-,*,/) to the top two
    /// values on self.stack,  op1 (+,-,*,/) op2
    fn bin_op_on_stack<F>(& mut self, f:&F) -> ()
        // vm::Value is a type alias for f64
        where F: FnOnce(vm::Value, vm::Value) -> vm::Value
        {
            let pop1 = self.stack.pop();
            // if pop2 is an f64 value pop1 must be one
            // as well because of the FIFO operation
            // principle of the stack.
            let pop2 = self.stack.pop();
            if let Some(op2) = pop2 {
                // here is the error, f is underscored in red:
                // cannot move out of `*f` which is behind a shared reference
                // move occurs because `*f` has type `F`, which does not implement the `Copy` trait
                self.stack.push(f(pop1.unwrap(), op2));
            }
        }

I also checked this variant:

            if let Some(op2) = pop2 {
                // same error message
                let res = f(pop1.unwrap(), op2);
                self.stack.push(res);
            }

5 posts - 4 participants

Read full topic

🏷️ rust_feed