January 2019
Beginner to intermediate
554 pages
13h 31m
English
Armed with the basics, it's time to put our knowledge to use! Here, we have a program that counts instances of words in a text file, which is passed to it as an argument. It's almost complete, but has a few bugs that the compiler catches and a couple of subtle ones. Here's our incomplete program:
// word_counter.rsuse std::env;use std::fs::File;use std::io::prelude::BufRead;use std::io::BufReader;#[derive(Debug)]struct WordCounter(HashMap<String, u64>);impl WordCounter { fn new() -> WordCounter { WordCounter(HashMap::new()); } fn increment(word: &str) { let key = word.to_string(); let count = self.0.entry(key).or_insert(0); *count += 1; } fn display(self) { for (key, value) in self.0.iter() { println!("{}: ...Read now
Unlock full access