I need to read a file, get each line, iterate over each line and check if that line contains any character from "aeiuo" and if it contains at least 2 of the characters "äüö".
Is this code idiomatic Rust? How do I check for several characters in a String
?
My attempt so far with some Google and code stealing:
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
fn main() {
// Create a path to the desired file
let path = Path::new("foo.txt");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
// Collect all lines into a vector
let reader = BufReader::new(file);
let lines: Vec<_> = reader.lines().collect();
for l in lines {
if (l.unwrap().contains("a")) {
println!("here is a");
}
}
}
1) "Is this code idiomatic Rust?"
Overall yes, it seems good. There is one minor point that you probably want to improve: you don't need to collect the lines into a vector to iterate on them. This is unwanted because it triggers unneeded memory allocations. Just reading the
lines()
iterator directly will work. (If you come from C++, you can forget about collecting things into intermediary vectors: think functional, think iterators!)becomes
2) "How do I check for several characters in a string?"
I suggest a simple approach based on
.any()
:Then you can go iterators all the way and write your main test as follows:
(Full code on the playground.)
This works, thanks to the nice people on /r/rust: