I'm still kind of getting used to dealing with strings in Rust and deciding when it makes sense to use to &str, when to clone a String, etc. Anyway, I hit an interesting compiler error. The error makes sense to me but the compiler's suggestion does not. Made a more minimal repro to show what I mean.
error[E0382]: borrow of moved value: `name`
--> src/main.rs:10:20
|
5 | let name = String::from("foo");
| ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
6 | let mut maps = Vec::<HashMap<String, String>>::new();
7 | for m in maps.iter_mut() {
| ------------------------ inside of this loop
8 | let _entry = m.entry(name);
| ---- value moved here, in previous iteration of loop
9 | }
10 | println!("{}", name);
| ^^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider moving the expression out of the loop so it is only moved once
|
7 ~ let mut value = m.entry(name);
8 ~ for m in maps.iter_mut() {
9 ~ let _entry = value;
|
help: consider cloning the value if the performance cost is acceptable
|
8 | let _entry = m.entry(name.clone());
| ++++++++
For more information about this error, try `rustc --explain E0382`.
Well I can't move the expression out of the loop because m isn't in scope there. This is clearer in the real code, but the whole point is that I'm checking if the key is present in the first map, and if not, checking the next map, and so on.
Is it expected that the compiler will occasionally make suggestions that don't work?
A browser interface to the Rust compiler to experiment with the language