Storing from inside a loop a borrowed value to container in outer scope?

后端 未结 2 1477
情歌与酒
情歌与酒 2020-12-11 19:07

I set myself a little task to acquire some basic Rust knowledge. The task was:

Read some key-value pairs from stdin and put them into a hashmap.

2条回答
  •  [愿得一人]
    2020-12-11 19:46

    The lifetime of 'text' is limited to the scope of the loop. The key-value pair that I'm extracting within the loop is therefore also bound to the loops boundaries. Thus, inserting them to the outer map would lead to an dangling pointer since 'text' will be destroyed after each iteration.

    Sounds right to me.

    Make an "owned copy" of the key value pair.

    An owned &str is a String:

    map.insert(kv_pair[0].to_string(), kv_pair[1].to_string());
    

    Edit

    The original code is below, but I've updated the answer above to be more idiomatic

    map.insert(String::from_str(kv_pair[0]), String::from_str(kv_pair[1]));
    

提交回复
热议问题