Error "cannot borrow as mutable because it is also borrowed as immutable" in Rust: how to fix?
Hello! I just started learning Rust and encountered a problem that I can't understand.
I have a simple program that takes a string and tries to first get its length, then change the first character:
```rust
fn main() {
let mut text = String::from("hello");
let first = &text[0..1]; // immutable reference
text.push_str(" world"); // attempt to mutable borrow
println!("First char: {}", first);
}
```
The compiler gives an error:
```
error[E0502]: cannot borrow `text` as mutable because it is also borrowed as immutable
```
I understand that Rust has borrowing rules: either one mutable reference or any number of immutable references. But why does my case violate this rule? After all, I first take an immutable reference to part of the string, and then
No answers yet.
Log in to leave an answer
Blogs
Java Application Security: Top 10 Vulnerabilities — Part 2