Cannot borrow String as mutable because it is also borrowed as immutable

I've been trying to do some simple problems in Rust lately and I can't seem to figure out how to resolve the following error. Link to source code.

error[E0502]: cannot borrow input as mutable because it is also borrowed as immutable
--> .\HardwoodSpecies.rs:19:35
|
19 | io::stdin().read_line(&mut input);
| ^^^^^^^^^^ mutable borrow occurs here
...
22 | if !treeMap.contains_key(&input) {
| ------- immutable borrow later used here
23 | treeMap.insert(&input, 1);
| ------ immutable borrow occurs here

error: aborting due to previous error

For more information about this error, try rustc --explain E0502.

My understanding is that on Line 19: io::stdin().read_line(&mut input); borrows a mutable reference to input and the lifetime of this mutable reference is the scope of the read_line function. After this function completes, my expectation is that I'm free to make as many immutable references to input. However, the compiler disagrees. Where is my understanding falling short?

treeMap.insert(&input, 1);

Here, you insert a reference to a string...

io::stdin().read_line(&mut input);

but then here, on the next iteration of the loop, you destroy the contents of said string, invalidating the reference.

You should insert a copy of the string into the map instead.

treeMap.insert(input.clone(), 1);
3 Likes

Perfect, thanks for the explanation!