Closed
Description
I just faced a compiler error when trying to clone a hashmap parameterized by a non-clone type. The error was a bit cryptic, about not expecting a reference, until I realized I've forgot to add the T: Clone
trait bound. Here is a minimal function reproducing my issue:
fn clone_map<T>(map1: &HashMap<String, T>) -> HashMap<String, T> {
map1.clone()
}
And here is the error I got:
7 | fn clone_map<T>(map1: &HashMap<String, T>) -> HashMap<String, T> {
| ------------------ expected `std::collections::HashMap<std::string::String, T>` because of return type
8 | map1.clone()
| ^^^^^^^^^^^^ expected struct `std::collections::HashMap`, found reference
|
= note: expected struct `std::collections::HashMap<std::string::String, T>`
found reference `&std::collections::HashMap<std::string::String, T>`
The code is available in the playground here. I was wondering if the compiler could deduce that the mistake here could be a missing trait bound and give that hint to the developer.