- I have a bunch of long immutable strings, which I would like to store in a
HashSet
. - I need a bunch of mappings with these strings as keys.
- I would like to use references to these strings as keys in these mappings to avoid copying strings.
This is how I managed to eventually get to this status. The only concern is this extra copy I need to make at line 5.
let mut strings: HashSet<String> = HashSet::new(); // 1
let mut map: HashMap<&String, u8> = HashMap::new(); // 2
// 3
let s = "very long string".to_string(); // 4
strings.insert(s.clone()); // 5
let s_ref = strings.get(&s).unwrap(); // 6
map.insert(s_ref, 5); // 7
To avoid this cloning I found two workarounds:
- Use
Rc
for string (adds overhead and code clutter) - Use unsafe code
Is there any sensible way to remove this excessive cloning?