I'm working on Project Euler 96 to teach myself Rust. I've written this code to read in the file and convert it into a vector of integers (Playground).
let file = File::open(&args[1]).expect("Sudoku file not found");
let reader = BufReader::new(file);
let x = reader
.lines()
.map(|x| x.unwrap())
.filter(|x| !x.starts_with("Grid"))
.flat_map(|s| s.chars().collect::<Vec<_>>()) // <-- collect here!
.map(|x| x.to_digit(10).unwrap())
.collect::<Vec<_>>();
This all works fine but I'm puzzled why I have to collect into a vector in my flat_map
(I'm assuming creating unneeded vectors which will be immediately destroyed is inefficient). If I don't collect, it doesn't compile:
error[E0515]: cannot return value referencing function parameter `s`
--> src/main.rs:13:23
|
13 | .flat_map(|s| s.chars())
| -^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `s` is borrowed here
The example from the docs shows almost the same code, but a collect is not required:
let words = ["alpha", "beta", "gamma"];
// chars() returns an iterator
let merged: String = words.iter()
.flat_map(|s| s.chars())
.collect();
assert_eq!(merged, "alphabetagamma");
So why is it different in my code?