The Complete Rust Programming Reference Guide

Book description

Design and implement professional-level programs by leveraging modern data structures and algorithms in Rust

Key Features

  • Improve your productivity by writing more simple and easy code in Rust
  • Discover the functional and reactive implementations of traditional data structures
  • Delve into new domains of Rust, including WebAssembly, networking, and command-line tools

Book Description

Rust is a powerful language with a rare combination of safety, speed, and zero-cost abstractions. This Learning Path is filled with clear and simple explanations of its features along with real-world examples, demonstrating how you can build robust, scalable, and reliable programs.

You'll get started with an introduction to Rust data structures, algorithms, and essential language constructs. Next, you will understand how to store data using linked lists, arrays, stacks, and queues. You'll also learn to implement sorting and searching algorithms, such as Brute Force algorithms, Greedy algorithms, Dynamic Programming, and Backtracking. As you progress, you'll pick up on using Rust for systems programming, network programming, and the web. You'll then move on to discover a variety of techniques, right from writing memory-safe code, to building idiomatic Rust libraries, and even advanced macros.

By the end of this Learning Path, you'll be able to implement Rust for enterprise projects, writing better tests and documentation, designing for performance, and creating idiomatic Rust code.

This Learning Path includes content from the following Packt products:

  • Mastering Rust - Second Edition by Rahul Sharma and Vesa Kaihlavirta
  • Hands-On Data Structures and Algorithms with Rust by Claus Matzinger

What you will learn

  • Design and implement complex data structures in Rust
  • Create and use well-tested and reusable components with Rust
  • Understand the basics of multithreaded programming and advanced algorithm design
  • Explore application profiling based on benchmarking and testing
  • Study and apply best practices and strategies in error handling
  • 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

If you are already familiar with an imperative language and now want to progress from being a beginner to an intermediate-level Rust programmer, this Learning Path is for you. Developers who are already familiar with Rust and want to delve deeper into the essential data structures and algorithms in Rust will also find this Learning Path useful.

Table of contents

  1. Title Page
  2. Copyright
    1. The Complete Rust Programming Reference Guide
  3. About Packt
    1. Why subscribe?
    2. Packt.com
  4. Contributors
    1. About the authors
    2. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get 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. Lists, Lists, and More Lists
    1. Linked lists
      1. A transaction log
      2. Adding entries
      3. Log replay
      4. After use
      5. Wrap up
        1. Upsides
        2. Downsides
    2. Doubly linked list
      1. A better transaction log
      2. Examining the log
        1. Reverse
      3. Wrap up
        1. Upsides
        2. Downsides
    3. Skip lists
      1. The best transaction log
        1. The list
      2. Adding data
        1. Leveling up
      3. Jumping around
      4. Thoughts and discussion
        1. Upsides
        2. Downsides
    4. Dynamic arrays
      1. Favorite transactions
      2. Internal arrays
      3. Quick access
      4. Wrap up
        1. Upsides
        2. Downsides
    5. Summary
    6. Further reading
  20. Robust Trees
    1. Binary search tree
      1. IoT device management
      2. More devices
      3. Finding the right one
        1. Finding all devices
      4. Wrap up
        1. Upsides
        2. Downsides
    2. Red-black tree
      1. Better IoT device management
      2. Even more devices
        1. Balancing the tree
      3. Finding the right one, now
      4. Wrap up
        1. Upsides
        2. Downsides
    3. Heaps
      1. A huge inbox
      2. Getting messages in
      3. Taking messages out
      4. Wrap up
        1. Upsides
        2. Downsides
    4. Trie
      1. More realistic IoT device management
      2. Adding paths
      3. Walking
      4. Wrap up
        1. Upsides
        2. Downsides
    5. B-Tree
      1. An IoT database
      2. Adding stuff
      3. Searching for stuff
        1. Walking the tree
      4. Wrap up
        1. Upsides
        2. Downsides
    6. Graphs
      1. The literal Internet of Things
      2. Neighborhood search
      3. The shortest path
      4. Wrap up
        1. Upsides
        2. Downsides
    7. Summary
  21. Exploring Maps and Sets
    1. Hashing
      1. Create your own
      2. Message digestion
      3. Wrap up
    2. Maps
      1. A location cache
        1. The hash function
      2. Adding locations
      3. Fetching locations
      4. Wrap up
        1. Upsides
        2. Downsides
    3. Sets
      1. Storing network addresses
      2. Networked operations
        1. Union
        2. Intersection
        3. Difference
      3. Wrap up
        1. Upsides
        2. Downsides
    4. Summary
    5. Further reading
  22. Collections in Rust
    1. Sequences
      1. Vec<T> and VecDeque<T>
        1. Architecture
        2. Insert
        3. Look up
        4. Remove
      2. LinkedList<T>
        1. Architecture
        2. Insert
        3. Look up
        4. Remove
      3. Wrap up
    2. Maps and sets
      1. HashMap and HashSet
        1. Architecture
        2. Insert
        3. Lookup
        4. Remove
      2. BTreeMap and BTreeSet
        1. Architecture
        2. Insert
        3. Look up
        4. Remove
      3. Wrap up
    3. Summary
    4. Further reading
  23. Algorithm Evaluation
    1. The Big O notation
      1. Other people's code
      2. The Big O
        1. Asymptotic runtime complexity
      3. Making your own
        1. Loops
        2. Recursion
      4. Complexity classes
        1. O(1)
        2. O(log(n))
        3. O(n)
        4. O(n log(n))
        5. O(n²)
        6. O(2n)
        7. Comparison
    2. In the wild
      1. Data structures
      2. Everyday things
      3. Exotic things
    3. Summary
    4. Further reading
  24. Ordering Things
    1. From chaos to order
      1. Bubble sort
      2. Shell sort
      3. Heap sort
      4. Merge sort
      5. Quicksort
    2. Summary
    3. Further reading
  25. Finding Stuff
    1. Finding the best
      1. Linear searches
      2. Jump search
      3. Binary searching
      4. Wrap up
    2. Summary
    3. Further reading
  26. Random and Combinatorial
    1. Pseudo-random numbers
      1. LCG
      2. Wichmann-Hill
      3. The rand crate
    2. Back to front
      1. Packing bags or the 0-1 knapsack problem
      2. N queens
    3. Advanced problem solving
      1. Dynamic programming
        1. The knapsack problem improved
      2. Metaheuristic approaches
        1. Example metaheuristic – genetic algorithms
    4. Summary
    5. Further reading
  27. Algorithms of the Standard Library
    1. Slicing and iteration
      1. Iterator
      2. Slices
    2. Search
      1. Linear search
      2. Binary search
    3. Sorting
      1. Stable sorting
      2. Unstable sorting
    4. Summary
    5. Further reading
  28. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: The Complete Rust Programming Reference Guide
  • Author(s): Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger
  • Release date: May 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781838828103