Created
December 30, 2018 10:55
Revisions
-
djhworld renamed this gist
Dec 30, 2018 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
djhworld created this gist
Dec 30, 2018 .There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,87 @@ use std::collections::HashMap; use std::io; use std::io::BufRead; struct Counter { items: HashMap<String, usize>, } impl Counter { fn new() -> Counter { return Counter { items: HashMap::new(), }; } fn add(&mut self, st: &str) { match self.items.get_mut(st) { Some(x) => { *x += 1; } None => { self.items.insert(st.to_owned(), 1); } } } fn render(&self) { for (key, val) in &self.items { println!("{}\t{}", val, key); } } } fn using_read_line_with_reuse(c: &mut Counter) { let st = io::stdin(); let mut stdin = st.lock(); let mut line = String::new(); loop { line.clear(); let r = stdin.read_line(&mut line); match r { Ok(0) => break, Ok(_) => { c.add(line.trim_end()); } Err(err) => { println!("{}", err); break; } }; } } fn using_read_line(c: &mut Counter) { let st = io::stdin(); let mut stdin = st.lock(); loop { let mut line = String::new(); let r = stdin.read_line(&mut line); match r { Ok(0) => break, Ok(_) => { c.add(line.trim_end()); } Err(err) => { println!("{}", err); break; } }; } } // uses lines() iterator fn using_bufread_lines(c: &mut Counter) { for r in io::stdin().lock().lines().filter_map(Result::ok) { c.add(r.as_str()); } } fn main() { let mut c = Counter::new(); // using_bufread_lines(&mut c); //using_read_line(&mut c); using_read_line_with_reuse(&mut c); c.render(); }