ch. 12 rust book

mail@pastecode.io avatar
unknown
rust
10 months ago
1.4 kB
3
Indexable
Never
// main.rs
use minigrep::run;

fn main() {
    let result = run();
    if let Err(e) = result {
        println!("{e}");
    }
}

---------
// lib.rs
use std::env;
use std::fs;
use std::path;
use std::str;
pub struct TextDir {
    path: path::PathBuf,
}
impl TextDir {
    pub fn build() -> Result<TextDir, Box<dyn std::error::Error>> {
        let cur_dir = std::env::current_dir()?;
        let text_dir = cur_dir.join("texts");
        Ok(TextDir { path: text_dir })
    }
    pub fn file(&self, path: &String) -> path::PathBuf {
        self.path.join(path)
    }
}
pub struct Config {
    name: String,
}
impl Config {
    pub fn name(vec: Vec<String>) -> Result<Config, &'static str> {
        let max_arg: usize = 2;
        if vec.len() < max_arg {
            return Err("1 Argument is required: file name.");
        }
        Ok(Config {
            name: vec[1].clone(),
        })
    }
}
pub fn run() -> Result<(), Box<dyn std::error::Error>> {
    let text_dir = TextDir::build().unwrap_or_else(|err| {
        println!("{err}");
        std::process::exit(1);
    });
    let args: Vec<String> = env::args().collect();
    let config = Config::name(args).unwrap_or_else(|err| {
        println!("{err}");
        std::process::exit(1);
    });
    let filepath = text_dir.file(&config.name);
    let open = fs::read(&filepath)?;
    let content = str::from_utf8(&open)?;
    println!("{content}");
    Ok(())
}
Leave a Comment