Skip to content

Instantly share code, notes, and snippets.

@rylev
Created January 26, 2022 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rylev/61ab2c537dc2223a0a75dd393652ef59 to your computer and use it in GitHub Desktop.
Save rylev/61ab2c537dc2223a0a75dd393652ef59 to your computer and use it in GitHub Desktop.
Rust in VS Code Example Code
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")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment