Skip to content

Cannot borrow as mutable despite DerefMut #51886

Closed
@smcmurray

Description

@smcmurray

May be related to #17501

use std::ops::{Deref, DerefMut};

struct Test(Box<FnMut()>);

impl Deref for Test {
    type Target = Box<FnMut()>;
    fn deref(&self)->&Self::Target {
        &self.0
    }
}

impl DerefMut for Test {
    fn deref_mut(&mut self)-> &mut Box<FnMut()> {
        &mut self.0
    }
}

fn main() {
    let mut t = Test(Box::new(move || ()));
    (t.0)();
    t();
}

Rust 2015:

error[E0596]: cannot borrow immutable `Box` content as mutable
  --> src/main.rs:21:5
   |
21 |     t();
   |     ^ cannot borrow as mutable

Rust 2018:

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/main.rs:21:5
   |
21 |     t();
   |     ^ cannot borrow as mutable

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions