Skip to content

Instantly share code, notes, and snippets.

@midnightcodr
Created April 9, 2021 01:19
Show Gist options
  • Save midnightcodr/3d9a32319b1297466525cfca3e5ff22a to your computer and use it in GitHub Desktop.
Save midnightcodr/3d9a32319b1297466525cfca3e5ff22a to your computer and use it in GitHub Desktop.
a simple cat implementation with rust, plus some customized error handling
// main.rs
use std::env;
use std::error::Error;
use std::fs;
use std::fmt;
#[derive(Debug)]
struct MyError(String);
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "application error: {}", self.0)
}
}
impl Error for MyError {}
fn main() {
let res = run();
match res {
Ok(_) => {}
Err(e) => println!("oops: {}", e),
}
}
fn run() -> std::result::Result<(), Box<dyn Error>> {
let filename = &env::args().skip(1).next();
if let Some(filename) = filename {
let text = fs::read_to_string(filename)?;
for line in text.lines() {
println!("{}", line);
}
Ok(())
} else {
Err(Box::new(MyError("please provide a file".into())))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment