Is there a way to mutate object through mutable reference in an immutable slice?

Viewed 154

I have &[&mut Foo]. Can I call &mut self-method of Foo within this slice?

1 Answers

No you cannot.

Immutable references are officially called “shared” references: you can have many shared references to a same object. On the other hand, mutable references are exclusive, so multiple mutable references to one object is not allowed. These rules are designed to help avoid data race.

Once an object is behind a shared reference, it is immutable. Otherwise you can effectively have multiple mutable references to a single object, which leads to data race.

If you really want such things, have a look at documentation for module std::cell.

Related