পাঠ ১২.৫

Environment variable নিয়ে কাজ

Working with Environment Variables

এখন minigrep-এ case-insensitive search যোগ করব। User IGNORE_CASE environment variable set করে দিলে সব search case-insensitive হবে — terminal session-এ একবার set করলেই হবে।

Failing test প্রথমে

src/lib.rsrust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}

আগের test-এর নাম এখন case_sensitive। নতুন case_insensitive — query "rUsT" দিয়ে "Rust:" এবং "Trust me." দু'টোই match হওয়ার expectation।

Implementation

src/lib.rsrust
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
}
  • query.to_lowercase() নতুন String বানায় — original &str-কে shadow করে।
  • line.to_lowercase().contains(&query)contains &str চায়, তাই &query
  • to_lowercase() basic Unicode handle করে, কিন্তু সব edge case 100% accurate না।

Config-এ ignore_case field

src/lib.rsrust
pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

env::var দিয়ে variable read

src/lib.rsrust
use std::env;

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();

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}
  • env::var("IGNORE_CASE") Result<String, VarError> দেয়।
  • .is_ok() — variable set থাকলে true (value যাই হোক), না থাকলে false। আমাদের শুধু presence/absence দরকার।

run-এ branch

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

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

Test করা

সাধারণ (case-sensitive):

$ cargo run -- to poem.txt
Are you nobody, too?
How dreary to be somebody!

IGNORE_CASE set করে:

$ IGNORE_CASE=1 cargo run -- to poem.txt
Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!

PowerShell-এ:

PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt
PS> Remove-Item Env:IGNORE_CASE  # unset

এই পাঠ থেকে যা শিখলে

  • std::env::var("NAME") + .is_ok() — environment variable presence check।
  • to_lowercase() — Unicode-aware lowercase; new String।
  • CLI flag-এর বদলে env var দিয়ে behavior switch — useful pattern।