Confusion about Rust HashMap and String borrowing

前端 未结 1 1137
轻奢々
轻奢々 2020-12-21 10:51

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

相关标签:
1条回答
  • 2020-12-21 11:28

    split_whitespace() doesn't give you two new Strings 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());
    
    0 讨论(0)
提交回复
热议问题