Rust first comprehensive practice

Ha read the file.

But divided into lib.rs and main.rs.

According to the document can not, through its own random tune, but the principles are not familiar with.

Inside routine code or find many.

src/lib.rs

use std::io::Read;
use std::error::Error;

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 })
    }
}

pub fn run(config: Config) -> Result<(), Box<Error>> {
    let mut file = std::fs::File::open(config.filename)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

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

    Ok(())

}

 

src/main.rs

use std::env;
use std::process;

extern crate minigrep;

fn main() {
    let args: Vec<String> = env::args().collect();
    let config = minigrep::Config::new(&args).unwrap_or_else(|err| {
    println!("Problem parsing arguments: {}", err);
    process::exit(1);
    });


    println!("Search for {}", config.query);
    println!("In file {}", config.filename);

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

Guess you like

Origin www.cnblogs.com/aguncn/p/11432554.html