# Working with environment variables Let's test with an Environment Variable that we will read s allowing case insensitive search! ### Step 1 - Test & Failing function ```rust //test module... 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)); } //... pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { //... copy search function } ``` This will fail because it can't find "RuSt", but could find "Rust" and "rust" which are differently cased. ### Step 2 - Making it pass ```rust pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut ret: Vec<&str> = Vec::new(); let up_query: String = query.to_uppercase(); // tp_uppercase Allocates to Heap a new String! for line in contents.lines() { if line.to_uppercase().contains(&up_query) { // pass a reference because we are using String not str ret.push(line.trim()); } } ret } ``` Now we transform everything to uppercase (could do to lowercase too), and treat every string as that case to ignore casing! ## Adding Environment Variables First we add the bool to check if a config is case sensitive ```rust pub struct Config { pub query: String, pub filename: String, pub case_sensitive: bool, } ``` Then we have to check if the environment variable is set: ```rust // Config implementation pub fn new(args: &[String]) -> Result { //... let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); Ok(Config { query, filename, case_sensitive }) } ``` `is_err` Returns false if the variable is found! So bool is false because it should not be `case_sensitive` the search. To test this out, I swapped to a powershell instead of windows cmdprompt terminal. ```bash $Env:VarName=Value # Adds variable to current session Remove-Item Env:VarName # Removes variables ``` === # Writing Errors to Standard Error instead of Standard Output `println!` writes to output terminal, but we have `stdout` and `stderr` so that users can filter. In the command line we see everything by default, but when we output to a file, that may not be the case or what is wanted ## Printing to Standard Error `eprintln!`, that's it, now it will print to command line but not to files output like `cargo run > output.txt` `> file.txt` redirects output to a file, we would see on command line only the rrors but in file the output.