Last active
November 30, 2017 11:58
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hello | |
World | |
!!!!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment