This program accepts an integer N, followed by N lines containing two strings separated by a space. I want to put those lines into a HashMap
using the first str
split_whitespace()
doesn't give you two new String
s containing (copies of) the non-whitespace parts of the input. Instead you get two references into the memory managed by input
, of type &str
. So when you then try to clear input
and read the next line of input into it, you try overwriting memory that's still being used by the hash map.
Why does split_whitespace
(and many other string methods, I should add) complicate matters by returning &str
? Because it's often enough, and in those cases it avoid unnecessary copies. In this specific case however, it's probably best to explicitly copy the relevant parts of the string:
map.insert(data[0].clone(), data[1].clone());