Open fishrockz opened 1 year ago
This issue still exists. Maybe map_entry
should only be applied when the key type is Copy
.
The following simple program reproduces this in rustc 1.80.0-nightly (804421dff 2024-06-07)
use std::collections::HashMap;
fn main() {
let mut hm:HashMap<String,bool> = HashMap::new();
let key = "hello".to_string();
if hm.contains_key(&key) {
let bval = hm.get_mut(&key).unwrap();
*bval = false;
} else {
hm.insert(key, true);
}
}
causing this error after fix:
error[E0382]: borrow of moved value: `key`
--> src/main.rs:9:31
|
5 | let key = "hello".to_string();
| --- move occurs because `key` has type `std::string::String`, which does not implement the `Copy` trait
6 | if let std::collections::hash_map::Entry::Vacant(e) = hm.entry(key) {
| --- value moved here
...
9 | let bval = hm.get_mut(&key).unwrap();
| ^^^^ value borrowed here after move
error: aborting due to 1 previous error
As @maxi0604 suggested, perhaps if the key is not Copy
the lint could simply warn about this but not attempt a fix. An autofix does not seem simple because the get_mut
line is now invalid - the key would need to have been cloned in the call to entry
for that to work.
When running
cargo clippy --fix
The code fails because I use the thing I test for in the hash map in the else. This seems fairly sensible so I am surprised this wasn't picked up already. Maybe I'm missing something silly.
Ether way the output suggested creating a issue so I have done
Meta
rustc --version --verbose
:To reproduce clone https://gitlab.com/girderstream/girderstream/-/commit/edc55aa923ad4fdb51e4494998c4b681b6fcb260 and run
cargo clippy --fix
This is the diff clippy suggests with
cargo clippy --fix --broken-code
https://gitlab.com/girderstream/girderstream/-/commit/f7cbc3b097d859805d1f27b56b0973fb3004e963which can be fixed with https://gitlab.com/girderstream/girderstream/-/commit/83422f677efb4eba8eb7a54da5cecc6022992d38 but is not always a good idea to add a
clone
.Its a shame you cant pass in a borrow to HashMap.entry()