Externalize logic into library crate

This commit is contained in:
Manuel Thalmann 2025-03-20 00:32:18 +01:00
parent c68a76f2e8
commit 6af1aad588
Signed by: manuth
SSH key fingerprint: SHA256:HsMLC+7kJWALP6YCYCoopxNbUnghwSGLVcG76SECT5c
2 changed files with 29 additions and 27 deletions
minigrep/src

26
minigrep/src/lib.rs Normal file
View file

@ -0,0 +1,26 @@
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
println!("With text:\n{contents}");
Ok(())
}

View file

@ -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,32 +14,8 @@ fn main() {
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
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.file_path)?;
println!("With text:\n{contents}");
Ok(())
}
struct Config {
query: String,
file_path: String,
}
impl Config {
fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}