Borrowed value does not live long enough inside a loop

Hi, I'm currently working on the 'department-employee' HashMap exercise recommended at the end of chapter 8 of the Rust Programming Book, I'm having a hard time understanding why wrapping the body of my reading_command function within a loop causes the command variable to have a lifetime issue, this is the function in question:

fn reading_command(company: &mut HashMap<&str, &str>) {
  loop {
    println!("Enter command:");
    let mut command = String::new();
    io::stdin().read_line(&mut command).expect("could not read command");
    let v: Vec<&str> = command.split_whitespace().collect();
    let employee_name = &v[1];
    let department = &v[3];
    company.insert(department, employee_name);
    for (key, value) in company {
      println!("{}: {}", key, value);

employee_name and department both become &str types, and no mutations to command that would cause a borrow/validity error occurs, I'm pretty sure what I'm missing is just a small change, since everything works as expected when the body isn't wrapped in a loop.

rest of code:

fn main() {
  let mut company = HashMap::new();
  reading_command(&mut company);

If it has anything to do with lifetimes, which I assume from the compiler messages, that would be explicable since I haven't gotten to that part of the book yet...

I appreciate any help!

There's a problem even without the loop, and this is indeed about lifetimes. Let me boil down a shorter version...

fn reading_command(company: &mut HashMap<&str, &str>) {
    let key = "key".to_string();
    let value = "value".to_string();
    company.insert(&key, &value);

The problem is that company contains references, and company lasts longer than the call to reading_command. Any references you put into company will have to have a lifetime longer than company -- they data they reference will have to last longer, or the references will end up pointing to unallocated data.

But the data in the key and value I created will go away at the end of the reading_command function. So I can't store references to them in company.

Similarly, you're creating a new String on every trip through your loop, and then storing references to it in company. But the String goes away at the end of the loop.

Store Strings instead. You can use the .to_string() method that I used in my shorter example.


I got it to work with Strings as you suggested. it helped solidify some of my understanding as well..couldn't have asked for a better reply, thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.