Skip to content

Unsafe &mut using RefCell #18566

@murarth

Description

@murarth

The following code will compile and run (and fail an assertion), when it should not compile:

use std::cell::RefCell;

struct A {
    a: RefCell<Vec<int>>,
}

fn main() {
    let mut a = A{a: RefCell::new(vec![1])};

    for i in a.a.borrow().iter() {
        let r = &mut a;
        r.a = RefCell::new(vec![2]);
        println!("{}", i);
    }
}

Notably, this version properly produces a compile error, recognizing the existing immutable borrow:

use std::cell::RefCell;

struct A {
    a: RefCell<Vec<int>>,
}

fn main() {
    let mut a = A{a: RefCell::new(vec![1])};
    let b = a.a.borrow();

    for i in b.iter() {
        let r = &mut a;
        r.a = RefCell::new(vec![2]);
        println!("{}", i);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions