Mastering Rust - Second Edition

Book description

Become proficient in designing, developing and deploying effective software systems using the advanced constructs of Rust

Key Features

  • Improve your productivity using the latest version of Rust and write simpler and easier code
  • Understand Rust's immutability and ownership principle, expressive type system, safe concurrency
  • Deep dive into the new doamins of Rust like WebAssembly, Networking and Command line tools

Book Description

Rust is an empowering language that provides a rare combination of safety, speed, and zero-cost abstractions. Mastering Rust ? Second Edition is filled with clear and simple explanations of the language features along with real-world examples, showing you how you can build robust, scalable, and reliable programs.

This second edition of the book improves upon the previous one and touches on all aspects that make Rust a great language. We have included the features from latest Rust 2018 edition such as the new module system, the smarter compiler, helpful error messages, and the stable procedural macros. You'll learn how Rust can be used for systems programming, network programming, and even on the web. You'll also learn techniques such as writing memory-safe code, building idiomatic Rust libraries, writing efficient asynchronous networking code, and advanced macros. The book contains a mix of theory and hands-on tasks so you acquire the skills as well as the knowledge, and it also provides exercises to hammer the concepts in.

After reading this book, you will be able to implement Rust for your enterprise projects, write better tests and documentation, design for performance, and write idiomatic Rust code.

What you will learn

  • Write generic and type-safe code by using Rust's powerful type system
  • How memory safety works without garbage collection
  • Know the different strategies in error handling and when to use them
  • Learn how to use concurrency primitives such as threads and channels
  • Use advanced macros to reduce boilerplate code
  • Create efficient web applications with the Actix-web framework
  • Use Diesel for type-safe database interactions in your web application

Who this book is for

The book is aimed at beginner and intermediate programmers who already have familiarity with any imperative language and have only heard of Rust as a new language. If you are a developer who wants to write robust, efficient and maintainable software systems and want to become proficient with Rust, this book is for you. It starts by giving a whirlwind tour of the important concepts of Rust and covers advanced features of the language in subsequent chapters using code examples that readers will find useful to advance their knowledge.

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. Mastering Rust Second Edition
  3. About Packt
    1. Why subscribe?
    2. Packt.com
  4. Contributors
    1. About the author
    2. About the reviewer
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. Getting the most out of this book
      1. Download the example code files
      2. Conventions used
    4. Get in touch
      1. Reviews
  6. Getting Started with Rust
    1. What is Rust and why should you care?
    2. Installing the Rust compiler and toolchain
      1. Using rustup.rs
    3. A tour of the language
      1. Primitive types
      2. Declaring variables and immutability
      3. Functions
      4. Closures
      5. Strings
      6. Conditionals and decision making
      7. Match expressions
      8. Loops
      9. User-defined types
        1. Structs
        2. Enums
      10. Functions and methods on types
        1. Impl blocks on structs
        2. Impl blocks for enums
      11. Modules, imports, and use statements
      12. Collections
        1. Arrays
        2. Tuples
        3. Vectors
        4. Hashmaps
        5. Slices
      13. Iterators
    4. Exercise – fixing the word counter
    5. Summary
  7. Managing Projects with Cargo
    1. Package managers
    2. Modules
      1. Nested modules
      2. File as a module
      3. Directory as module
    3. Cargo and crates
      1. Creating a new Cargo project
      2. Cargo and dependencies
      3. Running tests with Cargo
      4. Running examples with Cargo
      5. Cargo workspace
    4. Extending Cargo and tools
      1. Subcommands and Cargo installation
        1. cargo-watch
        2. cargo-edit
        3. cargo-deb
        4. cargo-outdated
      2. Linting code with clippy
      3. Exploring the manifest file – Cargo.toml
    5. Setting up a Rust development environment
    6. Building a project with Cargo – imgtool
    7. Summary
  8. Tests, Documentation, and Benchmarks
    1. Motivation for testing
    2. Organizing tests
      1. Testing primitives
        1. Attributes
        2. Assertion macros
    3. Unit tests
      1. First unit test
      2. Running tests
      3. Isolating test code
      4. Failing tests
      5. Ignoring tests
    4. Integration tests
      1. First integration test
      2. Sharing common code
    5. Documentation
      1. Writing documentation
      2. Generating and viewing documentation
      3. Hosting documentation
      4. Doc attributes
      5. Documentation tests
    6. Benchmarks
      1. Built-in micro-benchmark harness
      2. Benchmarking on stable Rust
    7. Writing and testing a crate – logic gate simulator
    8. Continuous integration with Travis CI
    9. Summary
  9. Types, Generics, and Traits
    1. Type systems and why they matter
    2. Generics
      1. Creating generic types
        1. Generic functions
        2. Generic types
      2. Generic implementations
      3. Using generics
    3. Abstracting behavior with traits
      1. Traits
      2. The many forms of traits
        1. Marker traits
        2. Simple traits
        3. Generic traits
        4. Associated type traits
        5. Inherited traits
    4. Using traits with generics – trait bounds
      1. Trait bounds on types
      2. Trait bounds on generic functions and impl blocks
      3. Using + to compose traits as bounds
      4. Trait bounds with impl trait syntax
    5. Exploring standard library traits
    6. True polymorphism using trait objects
      1. Dispatch
      2. Trait objects
    7. Summary
  10. Memory Management and Safety
    1. Programs and memory
    2. How do programs use memory?
    3. Memory management and its kinds
    4. Approaches to memory allocation
      1. The stack
      2. The heap
    5. Memory management pitfalls
    6. Memory safety
    7. Trifecta of memory safety
      1. Ownership
        1. A brief on scopes
        2. Move and copy semantics
      2. Duplicating types via traits
        1. Copy
        2. Clone
        3. Ownership in action
      3. Borrowing
        1. Borrowing rules
        2. Borrowing in action
      4. Method types based on borrowing
      5. Lifetimes
        1. Lifetime parameters
        2. Lifetime elision and the rules
        3. Lifetimes in user defined types
        4. Lifetime in impl blocks
        5. Multiple lifetimes
        6. Lifetime subtyping
        7. Specifying lifetime bounds on generic types
    8. Pointer types in Rust
      1. References – safe pointers
      2. Raw pointers
      3. Smart pointers
        1. Drop
        2. Deref and DerefMut
        3. Types of smart pointers
        4. Box<T>
      4. Reference counted smart pointers
        1. Rc<T>
        2. Interior mutability
        3. Cell<T>
        4. RefCell<T>
      5. Uses of interior mutability
    9. Summary
  11. Error Handling
    1. Error handling prelude
    2. Recoverable errors
      1. Option
      2. Result
    3. Combinators on Option/Result
      1. Common combinators
      2. Using combinators
      3. Converting between Option and Result
    4. Early returns and the ? operator
    5. Non-recoverable errors
      1. User-friendly panics
    6. Custom errors and the Error trait
    7. Summary
  12. Advanced Concepts
    1. Type system tidbits
      1. Blocks and expressions
      2. Let statements
      3. Loop as an expression
      4. Type clarity and sign distinction in numeric types
      5. Type inference
      6. Type aliases
    2. Strings
      1. Owned strings – String
      2. Borrowed strings – &str
      3. Slicing and dicing strings
      4. Using strings in functions
      5. Joining strings
      6. When to use &str versus String ?
    3. Global values
      1. Constants
      2. Statics
      3. Compile time functions – const fn
      4. Dynamic statics using the lazy_static! macro
    4. Iterators
      1. Implementing a custom iterator
    5. Advanced types
      1. Unsized types
      2. Function types
      3. Never type ! and diverging functions
      4. Unions
      5. Cow
    6. Advanced traits
      1. Sized and ?Sized
      2. Borrow and AsRef
      3. ToOwned
      4. From and Into
      5. Trait objects and object safety
      6. Universal function call syntax
      7. Trait rules
    7. Closures in depth
      1. Fn closures
      2. FnMut closures
      3. FnOnce closures
    8. Consts in structs, enums, and traits
    9. Modules, paths, and imports
      1. Imports
      2. Re-exports
      3. Selective privacy
    10. Advanced match patterns and guards
      1. Match guards
      2. Advanced let destructure
    11. Casting and coercion
    12. Types and memory
      1. Memory alignment
      2. Exploring the std::mem module
    13. Serialization and deserialization using serde
    14. Summary
  13. Concurrency
    1. Program execution models
    2. Concurrency
      1. Approaches to concurrency
        1. Kernel-based
        2. User-level
      2. Pitfalls
    3. Concurrency in Rust
      1. Thread basics
      2. Customizing threads
      3. Accessing data from threads
    4. Concurrency models with threads
      1. Shared state model
        1. Shared ownership with Arc
        2. Mutating shared data from threads
      2. Mutex
      3. Shared mutability with Arc and Mutex
        1. RwLock
      4. Communicating through message passing
        1. Asynchronous channels
        2. Synchronous channels
    5. thread-safety in Rust
      1. What is thread-safety?
      2. Traits for thread-safety
      3. Send
      4. Sync
    6. Concurrency using the actor model
    7. Other crates
    8. Summary
  14. Metaprogramming with Macros
    1. What is metaprogramming?
    2. When to use and not use Rust macros
    3. Macros in Rust and their types
      1. Types of macros
    4. Creating your first macro with macro_rules!
    5. Built-in macros in the standard library
    6. macro_rules! token types
    7. Repetitions in macros
    8. A more involved macro – writing a DSL for HashMap initialization
    9. Macro use case – writing tests
    10. Exercises
    11. Procedural macros
    12. Derive macros
    13. Debugging macros
    14. Useful procedural macro crates
    15. Summary
  15. Unsafe Rust and Foreign Function Interfaces
    1. What is safe and unsafe really?
      1. Unsafe functions and blocks
      2. Unsafe traits and implementations
    2. Calling C code from Rust
    3. Calling Rust code from C
    4. Using external C/C++ libraries from Rust
    5. Creating native Python extensions with PyO3
    6. Creating native extensions in Rust for Node.js
    7. Summary
  16. Logging
    1. What is logging and why do we need it?
    2. The need for logging frameworks
    3. Logging frameworks and their key features
    4. Approaches to logging
      1. Unstructured logging
      2. Structured logging
    5. Logging in Rust
      1. log – Rust's logging facade
      2. The env_logger
      3. log4rs
      4. Structured logging using slog
    6. Summary
  17. Network Programming in Rust
    1. Network programming prelude
    2. Synchronous network I/O
      1. Building a synchronous redis server
    3. Asynchronous network I/O
      1. Async abstractions in Rust
        1. Mio
        2. Futures
        3. Tokio
      2. Building an asynchronous redis server
    4. Summary
  18. Building Web Applications with Rust
    1. Web applications in Rust
    2. Typed HTTP with Hyper
      1. Hyper server APIs – building a URL shortener
      2. hyper as a client – building a URL shortener client
      3. Web frameworks
    3. Actix-web basics
    4. Building a bookmarks API using Actix-web
    5. Summary
  19. Interacting with Databases in Rust
    1. Why do we need data persistence?
    2. SQLite
    3. PostgreSQL
    4. Connection pooling with r2d2
    5. Postgres and the diesel ORM
    6. Summary
  20. Rust on the Web with WebAssembly
    1. What is WebAssembly?
    2. Design goals of WebAssembly
    3. Getting started with WebAssembly
      1. Trying it out online
      2. Ways to generate WebAssembly
    4. Rust and WebAssembly
      1. Wasm-bindgen
      2. Other WebAssembly projects
        1. Rust
        2. Other languages
    5. Summary
  21. Building Desktop Applications with Rust
    1. Introduction to GUI development
    2. GTK+ framework
    3. Building a hacker news app using gtk-rs
    4. Exercise
    5. Other emerging GUI frameworks
    6. Summary
  22. Debugging
    1. Introduction to debugging
      1. Debuggers in general
      2. Prerequisites for debugging
      3. Setting up gdb
      4. A sample program – buggie
      5. The gdb basics
      6. Debugger integration with Visual Studio Code
    2. RR debugger – a quick overview
    3. Summary
  23. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: Mastering Rust - Second Edition
  • Author(s): Rahul Sharma, Vesa Kaihlavirta
  • Release date: January 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781789346572