~irimi1/learning-rust

fb7ec1e9e060828105c40ef53acaeb2cb3b2ac69 — Manuel Groß 2 years ago 55f2f50
minigrep: Split program into main and lib

Remember to make all the things public in lib.rs
2 files changed, 30 insertions(+), 28 deletions(-)

A projects/minigrep/src/lib.rs
M projects/minigrep/src/main.rs
A projects/minigrep/src/lib.rs => projects/minigrep/src/lib.rs +27 -0
@@ 0,0 1,27 @@
use std::error::Error;
use std::fs;

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;

    println!("With text:\n{}", contents);

    Ok(())
}

pub struct Config {
    pub query: String,
    pub filename: String,
}

impl Config {
    pub fn new(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }
        let query = args[1].clone();
        let filename = args[2].clone();

        Ok(Config { query, filename })
    }
}

M projects/minigrep/src/main.rs => projects/minigrep/src/main.rs +3 -28
@@ 1,8 1,8 @@
use std::env;
use std::error::Error;
use std::fs;
use std::process;

use minigrep::Config;

fn main() {
    let args: Vec<String> = env::args().collect();



@@ 14,33 14,8 @@ fn main() {
    println!("Searching for {}", config.query);
    println!("In file {}", config.filename);

    if let Err(e) = run(config) {
    if let Err(e) = minigrep::run(config) {
        println!("Application error: {}", e);
        process::exit(1);
    }
}

fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;

    println!("With text:\n{}", contents);

    Ok(())
}

struct Config {
    query: String,
    filename: String,
}

impl Config {
    fn new(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }
        let query = args[1].clone();
        let filename = args[2].clone();

        Ok(Config { query, filename })
    }
}