vector - 如何从函数中的Vec返回单个元素?

标签 vector rust reference borrow-checker ownership

我是Rust的新手,我正在尝试建立一个界面,用户可以通过从可用文件列表中键入文件名来选择文件。
该函数应该返回与所选文件相对应的DirEntry:

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
}
但是,看来chosen是在这里借来的?我收到以下错误:
35 |     return chosen
   |            ^^^^^^ expected struct `DirEntry`, found `&DirEntry`
有什么方法可以“借用”吗?还是我必须实现CopyDirEntry特性?
如果很重要,我不在乎此方法后的Vec,因此,如果“借用” chosen破坏了Vec,那对我来说还可以(只要编译器同意)。

最佳答案

使用into_iter()而不是iter(),以便从迭代器中获得拥有的值,而不是引用。更改之后,代码将按预期进行编译和运行:

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
}

关于vector - 如何从函数中的Vec返回单个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65972577/

相关文章:

graphics - 自行车的旋转矩阵

C++ vector 操作优化

c++ - C++比较 vector 和列表

c# - 什么术语描述了解析代码 (c#) 以跟踪引用?

java - 当两个监控字段引用同一个对象时,为什么两个同步块(synchronized block)的行为就像我提供了不同的监控对象一样?

database - 学习 Cocoa 数据库开发的推荐资源?

c++ - 如何 std::find 使用比较对象?

rust - 如何将 &str 生命周期传递给 Box<dyn Fn()>

rust - 防止直接初始化类型别名

linux - 柴油编译卡在Lightsail上