Search code examples
vectorrustreferenceborrow-checkerownership

How to return a single element from a Vec from a function?


I'm new to Rust, and I'm trying to make an interface where the user can choose a file by typing the filename from a list of available files.

This function is supposed to return the DirEntry corresponding to the chosen file:

fn ask_user_to_pick_file(available_files: Vec<DirEntry>) -> DirEntry {
  println!("Which month would you like to sum?");
  print_file_names(&available_files);
  let input = read_line_from_stdin();

  let chosen = available_files.iter()
      .find(|dir_entry| dir_entry.file_name().into_string().unwrap() == input )
      .expect("didnt match any files");

  return chosen
}

However, it appears chosen is somehow borrowed here? I get the following error:

35 |     return chosen
   |            ^^^^^^ expected struct `DirEntry`, found `&DirEntry`

Is there a way I can "unborrow" it? Or do I have to implement the Copy trait for DirEntry?

If it matters I don't care about theVec after this method, so if "unborrowing" chosen destroys the Vec, thats okay by me (as long as the compiler agrees).


Solution

  • Use into_iter() instead of iter() so you get owned values instead of references out of the iterator. After that change the code will compile and work as expected:

    fn ask_user_to_pick_file(available_files: Vec<DirEntry>) -> DirEntry {
        println!("Which month would you like to sum?");
        print_file_names(&available_files);
        let input = read_line_from_stdin();
    
        let chosen = available_files
            .into_iter() // changed from iter() to into_iter() here
            .find(|dir_entry| dir_entry.file_name().into_string().unwrap() == input)
            .expect("didnt match any files");
    
        chosen
    }