I have a mutable reference to an Environment
struct which holds some data. My mutable functions on that struct (like create_data
) returns a read only reference to the newly created memory. I would like to add multiple pieces of data to my Environment
and return read only references to that data. However, when I try to do this with Rust immutable references I run into Rust’s “multiple mutable borrows” error.
Rust’s immutable references guarantee that the underlying data does not change. I’m not sure I need that guarantee. Is there a way I could get a “read-only” reference which does not guarantee the memory it points to is frozen?
Here’s a program that reproduces my issue with immutable references.
struct Environment {
data: Vec<Data>,
}
#[derive(Debug)]
struct Data(u8);
#[derive(Debug)]
struct DataRef<'a>(&'a Data);
impl Environment {
fn new() -> Environment {
Environment { data: Vec::new() }
}
fn create_data(&mut self, i: u8) -> &Data {
self.data.push(Data(i));
&self.data[self.data.len() - 1]
}
}
fn f<'a>(environment: &'a mut Environment) -> (DataRef<'a>, DataRef<'a>) {
let a = DataRef(environment.create_data(1));
let b = DataRef(environment.create_data(2));
(a, b)
}
fn main() {
println!("{:?}", f(&mut Environment::new()));
}
Compiler error:
error[E0499]: cannot borrow `*environment` as mutable more than once at a time
--> src/main.rs:24:21
|
23 | let a = DataRef(environment.create_data(1));
| ----------- first mutable borrow occurs here
24 | let b = DataRef(environment.create_data(2));
| ^^^^^^^^^^^ second mutable borrow occurs here
25 | (a, b)
26 | }
| - first borrow ends here
I’m not entirely sure how to title this question or how to search for answers.