为什么我不能将 Lines 迭代器收集到一个字符串向量中?

Pet*_*ron 5 string text-files rust

我正在尝试将文本文件的行读入Strings向量中,以便我可以不断循环遍历它们并将每一行写入通道进行测试,但编译器抱怨collect

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::Path;

fn main() {
    let file = File::open(Path::new("file")).unwrap();
    let reader = BufReader::new(&file);
    let _: Vec<String> = reader.lines().collect().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨:

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::Path;

fn main() {
    let file = File::open(Path::new("file")).unwrap();
    let reader = BufReader::new(&file);
    let _: Vec<String> = reader.lines().collect().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

没有.unwrap(), 编译器说:

error[E0282]: type annotations needed
 --> src/main.rs:9:30
  |
9 |     let lines: Vec<String> = reader.lines().collect().unwrap();
  |                              ^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type for `B`
  |
  = note: type must be known at this point
Run Code Online (Sandbox Code Playgroud)

我如何告诉 Rust 正确的类型?

lje*_*drz 5

由于您想直接收集到Vec<String>while Linesiterator is over Result<String, std::io::Error>,您需要稍微帮助类型推断:

let lines: Vec<String> = reader.lines().collect::<Result<_, _>>().unwrap();
Run Code Online (Sandbox Code Playgroud)

甚至只是:

let lines: Vec<_> = reader.lines().collect::<Result<_, _>>().unwrap();
Run Code Online (Sandbox Code Playgroud)

这样编译器就知道有一个带有Result<Vec<String>, io::Error>. 我认为这种情况将来可以改进,但现在类型推断无法推断出这一点。

  • 使用特征 [`FromIterator`](https://doc.rust-lang.org/std/result/enum.Result.html#impl-FromIterator%3CResult%3CA%2C%20E%3E%3E) 和 By推断 `String` 的方式。 (2认同)