Rust: Cannot borrow immutable reference as mutable
Problem Description
You are trying to mutate a reference that is immutable. In Rust, a mutable reference is not directly a mutable reference to an object but a unique reference to a mutable location.
Example
fn change_str(s: &mut str) { // ... } fn main() { let s = "immutable"; change_str(&mut s); // error: cannot borrow immutable borrowed content as mutable }
In this example, the type of s
is actually str
, which means the reference you are passing to change_str
is mut str
. This is not allowed because s
is immutable.
Solution
To fix the code, you can either make s
mutable or use a mutable reference to the underlying data. For example:
fn change_str(s: &mut str) { // ... } fn main() { let mut s = "mutable"; change_str(&mut s); // okay }
Alternatively, you can use a mutable reference to the underlying data:
fn change_str(s: &mut str) { // ... } fn main() { let s = "immutable"; change_str(&mut s.as_mut_str()); // okay }
Komentar