Skip to content

Instantly share code, notes, and snippets.

@turboMaCk
Last active November 30, 2017 11:58
Show Gist options
  • Save turboMaCk/e6961029ea3c8002f500d41560aa5091 to your computer and use it in GitHub Desktop.
Save turboMaCk/e6961029ea3c8002f500d41560aa5091 to your computer and use it in GitHub Desktop.
Simple rust program which deals with file reads in 3 different ways
// This program will read test.txt file and print it line by line
// implemented in 3 different ways
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
fn main() {
// Procedural
let f = File::open("test.txt").unwrap();
let file = BufReader::new(&f);
for line in file.lines() {
let l = line.unwrap();
println!("{}", l);
}
// Pattern matching
match File::open("test.txt") {
Ok(f) => {
let file = BufReader::new(&f);
for line in file.lines() {
match line {
Ok(l) => {
println!("{}", l);
}
Err(e) => {
println!("{}", e);
}
}
}
}
Err(e) => {
println!("{}", e);
}
};
// Monad
File::open("test.txt")
.and_then(|f| BufReader::new(f).lines().into_iter().collect::<Result<Vec<std::string::String>, std::io::Error>>())
.map(|lines| {
for l in lines {
println!("{}", l);
};
}).unwrap();
}
Hello
World
!!!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment