Rust compiler borrow checker
Compiler borrow checker constraints
The Rust program below gives the compiler errors. Look at the main function and try to understand the errors and suggest a possible fix.
Code
fn main() { let mut d1 = Dictionary.new(); d1.add_word("hello"); d1.add_word("world!"); } struct Dictionary { data: Vec<String>, } impl Dictionary { fn new() -> Self { Dictionary { data: Vec::new() } } fn add_word(&mut self, word: &str) { self.data.push(word.to_string()); } }
Error messages
- Cannot borrow
self
as mutable more than once at a time -- src/main.rs:46:29 - for
order_id
inmut self.map_order_id_position
----- - The only way this is possible except for unsafe code is that the resulting reference is somehow derived from the incoming reference (for example, it references some field inside the object).
- The
add_word
method gives these 5 errors - Cannot borrow
cursor
as mutable more than once at a time. - Since Rust no longer supports immutable struct fields and apparently since the borrow checker does not perform interprocedural analysis, the compiler acts as if one of the
mut
. - In practice, this means Rust's borrow checker will only allow at most one call to some_method before the struct becomes permanently mutably borrowed and thus unusable.
Conclusion
The Rust compiler borrow checker is a powerful tool that helps to ensure the memory safety of Rust programs. However, it can sometimes be difficult to understand the errors that the borrow checker generates. In this case, the error is due to the fact that the add_word
method borrows the self
parameter mutably. This means that the self
parameter cannot be borrowed again until the add_word
method returns. The fix is to move the add_word
method to the Dictionary
struct. This will allow the add_word
method to borrow the self
parameter mutably without violating the borrow checker's rules.
Comments