簡體   English   中英

為什么不能將Lines迭代器收集到Strings向量中?

[英]Why can't I collect the Lines iterator into a vector of Strings?

我正在嘗試將文本文件的行讀取為String的向量,以便可以不斷地在它們上循環並將每行寫入測試的通道,但是編譯器抱怨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();
}

編譯器抱怨:

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

沒有.unwrap() ,編譯器會說:

error[E0277]: a collection of type `std::vec::Vec<std::string::String>` cannot be built from an iterator over elements of type `std::result::Result<std::string::String, std::io::Error>`
 --> src/main.rs:9:45
  |
9 |     let lines: Vec<String> = reader.lines().collect();
  |                                             ^^^^^^^ a collection of type `std::vec::Vec<std::string::String>` cannot be built from `std::iter::Iterator<Item=std::result::Result<std::string::String, std::io::Error>>`
  |
  = help: the trait `std::iter::FromIterator<std::result::Result<std::string::String, std::io::Error>>` is not implemented for `std::vec::Vec<std::string::String>`

如何告訴Rust正確的類型?

由於您想在Lines迭代器遍歷Result<String, std::io::Error>同時直接收集到Vec<String> ,因此需要一點點幫助類型推斷:

let lines: Vec<String> = reader.lines().collect::<Result<_, _>>().unwrap();

甚至只是:

let lines: Vec<_> = reader.lines().collect::<Result<_, _>>().unwrap();

這樣,編譯器知道存在一個中間步驟,其中包含Result<Vec<String>, io::Error> 我認為這種情況將來可能會得到改善,但是現在類型推斷無法推斷出這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM