use std::error::Error;
use std::fs;
use std::env;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
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();
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
println!("{}", case_sensitive);
Ok(Config { query, filename, case_sensitive })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.filename)?;
let results = if config.case_sensitive {
search(&config.query, &contents)
} else {
search_case_insensitive(&config.query, &contents)
};
for line in results {
println!("{}", line);
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
A question to the code above. I use the "env::var" CASE_INSENSITIVE to check if I want to use the case sensitive search function or the case insensitive function to search for a String.
So for example ….. cargo run to poem.txt > output.txt
When I started my IDE fresh (Visual Studio Code) and I compile for the first time, is_err() returns true, because of an Error which follows from not initializing my environment variable yet.
So now I type "set CASE_INSENSITIVE=1" and then "cargo run to poem.txt > output.txt" and everything is fine. But when I want to use the sensitive search function again, I tried "set CASE_INSENSITIVE=0" but that won't work.
So what am I missing here?
Thank you for your help out in front....