Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Rust

You're reading from   Mastering Rust Learn about memory safety, type system, concurrency, and the new features of Rust 2018 edition

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher Packt
ISBN-13 9781789346572
Length 554 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Vesa Kaihlavirta Vesa Kaihlavirta
Author Profile Icon Vesa Kaihlavirta
Vesa Kaihlavirta
Rahul Sharma Rahul Sharma
Author Profile Icon Rahul Sharma
Rahul Sharma
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

Preface 1. Getting Started with Rust FREE CHAPTER 2. Managing Projects with Cargo 3. Tests, Documentation, and Benchmarks 4. Types, Generics, and Traits 5. Memory Management and Safety 6. Error Handling 7. Advanced Concepts 8. Concurrency 9. Metaprogramming with Macros 10. Unsafe Rust and Foreign Function Interfaces 11. Logging 12. Network Programming in Rust 13. Building Web Applications with Rust 14. Interacting with Databases in Rust 15. Rust on the Web with WebAssembly 16. Building Desktop Applications with Rust 17. Debugging 18. Other Books You May Enjoy

Exercise – fixing the word counter

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.rs

use 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!("{}: {}", key, value);
}
}
}

fn main() {
let arguments: Vec<String> = env::args().collect();
let filename = arguments[1];
println!("Processing file: {}", filename);

let file = File::open(filenam).expect("Could not open file");
let reader = BufReader::new(file);

let mut word_counter = WordCounter::new();

for line in reader.lines() {
let line = line.expect("Could not read line");
let words = line.split(" ");
for word in words {
if word == "" {
continue
} else {
word_counter.increment(word);
}
}
}

word_counter.display();
}

Go ahead and type the program into a file; try to compile and fix all the bugs with the help of the compiler. Try to fix one bug at a time and get feedback from the compiler by recompiling the code. The point of this exercise, in addition to covering the topics of this chapter, is to make you more comfortable with the error messages from the compiler, which is an important mental exercise in getting to know more about the compiler and how it analyzes your code. You might also be surprised to see how the compiler is quite smart in helping you removing errors from the code.

Once you are done fixing the code, here are some exercises for you to try so that you can flex your muscles a bit further:

  • Add a filter parameter to the display method of WordCounter for filtering the output based on the count. In other words, display a key/value pair only if the value is greater than that filtering value.
  • Since HashMaps store their values randomly, the output is also random every time you run the program. Try to sort the output. The HashMap's values method may be useful.
  • Take a look at the display method's self parameter. What happens if you remove the & operator before self?
You have been reading a chapter from
Mastering Rust - Second Edition
Published in: Jan 2019
Publisher: Packt
ISBN-13: 9781789346572
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime