Mastering Rust
eBook - ePub

Mastering Rust

  1. 354 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Mastering Rust

About this book

Discover the powerful, hidden features of Rust you need to build robust, concurrent, and fast applicationsAbout This Book• Learn how concurrency works in Rust and why it is safe• Get to know the different philosophies of error handling and how to use them wisely• After reading this book, you will be able to migrate your legacy C or C++ application to a Rust environmentWho This Book Is ForThe target audience would be readers having knowledge of other programming languages and are able to work fluently in the operating system of their choice, be it Linux, OS X or Windows. Since Rust is a rather new language, they are interested in programming beyond simply using it for work. The book focuses on intermediate and advanced features of Rust.What You Will Learn• Implement unit testing patterns with the standard Rust tools• Get to know the different philosophies of error handling and how to use them wisely• Appreciate Rust's ability to solve memory allocation problems safely without garbage collection• Get to know how concurrency works in Rust and use concurrency primitives such as threads and message passing• Use syntax extensions and write your own• Create a Web application with Rocket• Use Diesel to build safe database abstractionsIn DetailIf concurrent programs are giving you sleepless nights, Rust is your go-to language. Being one of the first ever comprehensive books on Rust, it is filled with real-world examples and explanations, showing you how you can build scalable and reliable programs for your organization.We'll teach you intermediate to advanced level concepts that make Rust a great language. Improving performance, using generics, building macros, and working with threads are just some of the topics we'll cover. We'll talk about the official toolsets and ways to discover more. The book contains a mix of theory interspersed with hands-on tasks, so you acquire the skills as well as the knowledge. Since programming cannot be learned by just reading, we provide exercises (and solutions) to hammer the concepts in.After reading this book, you will be able to implement Rust for your enterprise project, deploy the software, and will know the best practices of coding in Rust.Style and approachThis book is your one stop guide to the Rust programming language and covers advanced-level concepts in a detailed manner using real-world examples.

Tools to learn more effectively

Saving Books

Saving Books

Keyword Search

Keyword Search

Annotating Text

Annotating Text

Listen to it instead

Listen to it instead

Solutions and Final Words

You've come a long way, well done! You've learned a new language that probably had quite a few paradigms you hadn't met before. In this chapter, we'll wrap up the book with a short recap of every chapter, along with sample solutions to all exercises.

Chapter 1 - Getting Your Feet Wet

Rust is a language stewarded by Mozilla Research. It focuses on zero-cost abstractions and compile-time safety. Zero-cost abstractions refer to having modern high-level programming techniques available without creating any runtime overhead. Access to resources is secured by the compiler by a system of lifetimes and borrowing, which makes memory access safe without requiring a garbage collector.
The official Rust implementation comes in three forms: nightly, beta, and stable. The nightly branch is built automatically every night from the latest source code. Every six weeks, a release happens: beta version becomes the new stable, and a new beta version is branched off the nightly version. This does not imply that all the features from nightly go to stable every six weeks, rather, only those that are deemed to be stable. People should generally reach for the stable version but nightly has several nice but unstable features, so it is sometimes used.
rustup is the official distribution system for the Rust compiler and the Cargo package manager. It supports fetching and locally installing various Rust components and toolchains, and also enables flexible switching between the nightly, beta, and stable versions.
Rust's main abstraction mechanism is functions, defined with the fn keyword. Variables default to non-mutable, and variable bindings are defined with the let keyword. Mutability can be explicitly requested with let mut. Conditional branching is done with if, which is quite similar to other languages. Low-level loops can be written using loop and while, and higher-level looping via iterators is done with for. Compound data with one or more fields is formed with struct, while compound data with single variants is defined with enum.
Primitive types in Rust include Booleans (bool), various integers (usize, isize, u8, i8, u16, i16, u32, i32, u64, and i64), floats (f32 and f64), characters and string slices (char and str), fixed size arrays ([T; N]), slices (&[T]), tuples ((T1, T2, ...)), and functions (fn(T1, T2, ...) → R).
The standard library has two data structures for dynamic data: Vectors and HashMaps. Vectors offer dynamically sized arrays, while HashMaps are key-to-value mappings.

Exercise - fix the word counter

Here's a working version of the word counter. We have added the missing use statement and missing types, missing pointer syntax, and a missing mutability flag:
 use std::env;
use std::fs::File;
use std::io::prelude::BufRead;
use std::io::BufReader;
use std::collections::HashMap;

#[derive(Debug)]
struct WordStore (HashMap<String, u64>);

impl WordStore {
fn new() -> WordStore {
WordStore (HashMap::new())
}

fn increment(&mut self, 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();
println!("args 1 {}", arguments[1]);
let filename = arguments[1].clone();

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

let mut word_store = WordStore::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_store.increment(word);
}
}
}

word_store.display();
}

Chapter 2 - Using Cargo to Build Your First Program

The Cargo tool is the official package manager and build tool. It allows configuring package dependencies, building, running, and testing Rust software. Cargo is extensible, so additional functionality can be added via third-party packages.
Projects are configured in a single file, Cargo.toml. TOML is a configuration language that is essentially an INI, a file format extended with tree forms, lists, and dictionaries.
The de facto Rust code formatter tool is rustfmt. Clippy is a tool that can make additional style and pedantic checks on your codebase. It requires the nightly compiler as it works via compiler plugins. Racer does lookups into library code, giving code completion and tooltips. It requires Rust's source code to be available, which can be installed locally with rustup. All of these programs are written in Rust, and can be installed with Cargo.
These programs form the backbone for editor integration. Visual Code Studio, Emacs, Vim, and Atom all have plugins that provide good Rust support, and the list of editors with good Rust support is growing. https://areweideyet.com should contain up-to-date information about the current situation.

Exercise - starting our project

  1. Initialize a Cargo binary project, call it whatever you want (but I will name the game fanstr-buigam, short for fantasy strategy building game).
Solution:
 cargo init fanstrbuigam -bin 
  1. Check cargo.toml and fill in your name, e-mail, and description of the project.
Solution: Cargo.toml should have name, e-mail, description in the [package] section.
  1. Try out the Cargo build, test, and run commands.
Solution: cargo build/cargo test/cargo run.

Chapter 3 - Unit Testing and Benchmarking

Unit tests are a neat way to increase and maintain code quality. Rust supports basic unit testing in its core package. Test functions are annotated with #[test]. Two macros, assert! and assert_eq!, can be used to declare the expected function results. The #[should_panic] annotation can be used to define that a test should fail with a panic. Unit tests are placed in the same file as the code they test. The test code can be separated from the actual code by putting it in a separate module annotated with #[cfg_test].
Integration tests go into a separate tests/directory in a Rust project. These are meant for testing larger portions of code. Unlike unit tests, integration tests run as if they were consumers of library code of the project. They are black box tests.
Documentation tests are a third form of tests. They are meant for making runnable test code in module documentation. These tests are marked in markdown style by enclosing the test code in ```. This can be used in module-level (//! comments) or function-level (/// comments).
The fourth form is benchmark tests. They work somewhat like unit tests. Benchmark functions are annotated with #[bench] and take a Bencher object, which comes from the test crate. Benchmarks are not a s...

Table of contents

  1. Title Page
  2. Copyright
  3. Credits
  4. About the Author
  5. About the Reviewer
  6. www.PacktPub.com
  7. Preface
  8. Getting Your Feet Wet
  9. Using Cargo to Build Your First Program
  10. Unit Testing and Benchmarking
  11. Types
  12. Error Handling
  13. Memory, Lifetimes, and Borrowing
  14. Concurrency
  15. Macros
  16. Compiler Plugins
  17. Unsafety and Interfacing with Other Languages
  18. Parsing and Serialization
  19. Web Programming
  20. Data Storage
  21. Debugging
  22. Solutions and Final Words

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn how to download books offline
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 990+ topics, we’ve got you covered! Learn about our mission
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more about Read Aloud
Yes! You can use the Perlego app on both iOS and Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app
Yes, you can access Mastering Rust by Vesa Kaihlavirta in PDF and/or ePUB format, as well as other popular books in Computer Science & Object Oriented Programming. We have over one million books available in our catalogue for you to explore.