lotsoftools

Understanding Rust Error E0386

Rust Error E0386 Overview

Rust Error E0386 occurs when an attempt is made to mutate the target of a mutable reference stored inside an immutable container. In other words, you are trying to change data within a mutable reference, but the container holding that reference is immutable, preventing any modifications.

Example of Rust Error E0386

Consider the following code example, which generates Rust Error E0386:

```
#![allow(unused)]
fn main() {
  let mut x: i64 = 1;
  let y: Box<_> = Box::new(&mut x);
  **y = 2; // error, cannot assign to data in an immutable container
}
```

Fixing Rust Error E0386

This error can be fixed through two possible solutions:

1. Make the container mutable

Simply change the container to a mutable type, allowing modifications to its contents. In the given example, this can be achieved by adding the `mut` keyword to the variable declaration of `y`:

```
#![allow(unused)]
fn main() {
  let mut x: i64 = 1;
  let mut y: Box<_> = Box::new(&mut x);
  **y = 2;
}
```

2. Use a type with interior mutability

Interior mutability types, such as `Cell` or `RefCell`, allow for mutations within an immutable container. Here's how to apply this solution to the example code:

```
#![allow(unused)]
fn main() {
  use std::cell::Cell;

  let x: i64 = 1;
  let y: Box<Cell<_>> = Box::new(Cell::new(x));
  y.set(2);
}
```