Created
January 26, 2022 17:30
-
-
Save rylev/61ab2c537dc2223a0a75dd393652ef59 to your computer and use it in GitHub Desktop.
Rust in VS Code Example Code
This file contains hidden or 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 characters
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