How to put type annotation in map / collect command?

I have this code

fn load_file() -> Vec<String> {
  let path = Path::new("foo.txt");

  let mut file = BufferedReader::new(File::open(&path));
  file.lines().map(|x| x.unwrap()).collect();
}

fn main() {
  let data = load_file();
  println!("DATA: {}", data[0]);
}

When I try to compile it, I get this error

unable to infer enough type information about `_`; type annotations required

in line .collect.

In fact, if I change the function load_filethis way

fn load_file() -> Vec<String> {
  let path = Path::new("foo.txt");

  let mut file = BufferedReader::new(File::open(&path));
  let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
  return lines;
}

The code compiles smoothly. However, this solution is not sufficiently "rusty" (termination of the function with a return is not recommended).

Is it possible to put a type annotation directly in a statement file.lines().map(|x| x.unwrap()).collect();?

+4
source share
2 answers

In fact, your problem was somewhat less noticeable. This does not compile (your source code snippet):

fn load_file() -> Vec<String> {
  let path = Path::new("foo.txt");

  let mut file = BufferedReader::new(File::open(&path));
  file.lines().map(|x| x.unwrap()).collect();
}

fn main() {
  let data = load_file();
  println!("DATA: {}", data[0]);
}

But it does:

fn load_file() -> Vec<String> {
  let path = Path::new("foo.txt");

  let mut file = BufferedReader::new(File::open(&path));
  file.lines().map(|x| x.unwrap()).collect()
}

fn main() {
  let data = load_file();
  println!("DATA: {}", data[0]);
}

Can you notice the subtle difference? (this is just a semicolon in the last line load_file())

Rust , . , collect()! "" , collect() load_file() . ; , , ( , () Vec<String>).

+8

:

fn collect<B: FromIterator<<Self as Iterator>::Item>>(self) -> B

( : , . ), , B.

, func::<T, U ...>()

load_file :

fn load_file() -> Vec<String> {
  let path = Path::new("foo.txt");

  let mut file = BufferedReader::new(File::open(&path));
  file.lines().map(|x| x.unwrap()).collect::<Vec<String>>()

}
+4

Source: https://habr.com/ru/post/1570914/


All Articles