I'm attempting to construct a map from string prefixes to string suffixes and am making a bunch of string copies I'd prefer to avoid. Here's my code right now:
fn collect_matching_words(mut words: Vec<String>) -> HashMap<String, Vec<String>> {
let mut collected_words = HashMap::new();
for word in words.drain(..) {
let (prefix, suffix) = word.split_at(1);
collected_words.entry(suffix.to_owned()).or_insert(Vec::new()).push(prefix.to_owned())
}
collected_words
}
Every time I'm doing a lookup where the suffix is already present, I'm copying the suffix string for no good reason. At least in theory, it seems to me a hasher could handle both &str
and String
and only do the string copy when the key is not present. Is there a way to do that?