Skip to content

Bad interaction of smart pointers, auto-deref and closures #27106

Closed
@RalfJung

Description

@RalfJung

The following code does not compile:

use std::rc::Rc;
use std::cell::RefCell;

pub struct Callbacks {
    callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
}

impl Callbacks {
    pub fn call(&mut self, val: i32) {
        for callback in self.callbacks.iter() {
            let mut closure = callback.borrow_mut();
            closure(val);
        }
    }
}

(Playpen)

It says: "cannot borrow immutable borrowed content as mutable".

Instead, I have to explicitly dereference and borrow the closure in the loop, with (&mut *closure)(val). Typically, Rust performs this automatically, so I expected that to also happen in this case. At the very least, the error message should be improved, as currently, it doesn't help with the actual issue at all.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions