Skip to content

Instantly share code, notes, and snippets.

@rylev
Created January 26, 2022 17:30

Revisions

  1. rylev created this gist Jan 26, 2022.
    37 changes: 37 additions & 0 deletions counter.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    use std::collections::HashMap;

    fn main() -> Result<(), Box<dyn std::error::Error>> {
    let path = std::env::args()
    .skip(1)
    .next()
    .ok_or("Must supply name of file as first argument")?;
    let contents = std::fs::read_to_string(path)?;
    let counter = Counter::new(&contents);

    loop {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer)?;
    let word = buffer.trim();
    println!("count: {}", counter.get_count(word));
    buffer.clear();
    }
    }

    struct Counter<'a> {
    words: HashMap<&'a str, usize>,
    }

    impl<'a> Counter<'a> {
    fn new(contents: &'a str) -> Counter<'a> {
    let mut words = HashMap::<&str, usize>::new();
    for word in contents.split(" ") {
    *words.entry(word).or_default() += 1;
    }

    Self { words }
    }

    fn get_count(&self, word: &str) -> usize {
    todo!("implement this method")
    }
    }