### Install a Binary Crate with cargo install Source: https://doc.rust-lang.org/book/ch14-04-installing-binaries.html Use this command to install a binary crate, such as `ripgrep`, from crates.io. The output shows the installation progress and the final location of the executable. ```bash $ cargo install ripgrep Updating crates.io index Downloaded ripgrep v14.1.1 Downloaded 1 crate (213.6 KB) in 0.40s Installing ripgrep v14.1.1 --snip-- Compiling grep v0.3.2 Finished `release` profile [optimized + debuginfo] target(s) in 6.73s Installing ~/.cargo/bin/rg Installed package `ripgrep v14.1.1` (executable `rg`) ``` -------------------------------- ### Install rustup on Linux or macOS Source: https://doc.rust-lang.org/book/ch01-01-installation.html Run this command in your terminal to download and execute the rustup installation script. It installs the latest stable version of Rust. ```bash $ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### Successful rustup installation message Source: https://doc.rust-lang.org/book/ch01-01-installation.html This message confirms that rustup has been successfully installed. ```text Rust is installed now. Great! ``` -------------------------------- ### Run Program with Arguments Source: https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html Example of executing the Rust program with specific command-line arguments and observing the output. ```bash $ cargo run -- test sample.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep test sample.txt` Searching for test In file sample.txt ``` -------------------------------- ### Guessing Game Output Example Source: https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html This shows an example of the guessing game's output when run, demonstrating successful guesses and how non-numeric input causes a panic. ```Shell $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.23s Running `target/debug/guessing_game` Guess the number! The secret number is: 59 Please input your guess. 45 You guessed: 45 Too small! Please input your guess. 60 You guessed: 60 Too big! Please input your guess. 59 You guessed: 59 You win! Please input your guess. quit thread 'main' panicked at src/main.rs:28:47: Please type a number!: ParseIntError { kind: InvalidDigit } note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` -------------------------------- ### Create Workspace Directory Source: https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html Start by creating a new directory for your workspace. This will be the root directory for all related packages. ```bash $ mkdir add $ cd add ``` -------------------------------- ### String Slices: Omitting Start Index Source: https://doc.rust-lang.org/book/ch04-03-slices.html Shows how to create a string slice starting from the beginning of the string by omitting the start index. ```rust fn main() { let s = String::from("hello"); let slice = &s[0..2]; let slice = &s[..2]; } ``` -------------------------------- ### List Installed Rust Toolchains Source: https://doc.rust-lang.org/book/appendix-07-nightly-rust.html View all installed Rust toolchains, including stable, beta, and nightly versions, and identify the default toolchain. ```bash > rustup toolchain list stable-x86_64-pc-windows-msvc (default) beta-x86_64-pc-windows-msvc nightly-x86_64-pc-windows-msvc ``` -------------------------------- ### Example Usage of `println!` Macro Source: https://doc.rust-lang.org/book/ch20-05-macros.html Demonstrates calling the `println!` macro with a single argument and with two arguments, highlighting its variable argument capability. ```Rust println!("hello"); println!("hello {}", name); ``` -------------------------------- ### Check Rust installation version Source: https://doc.rust-lang.org/book/ch01-01-installation.html Verify that Rust is installed correctly by checking its version. This command should output the compiler version, commit hash, and date. ```bash $ rustc --version ``` -------------------------------- ### Creating Basic String Slices Source: https://doc.rust-lang.org/book/ch04-03-slices.html Demonstrates creating string slices from a String using explicit start and end indices. ```rust fn main() { let s = String::from("hello world"); let hello = &s[0..5]; let world = &s[6..11]; } ``` -------------------------------- ### Running the Program Source: https://doc.rust-lang.org/book/ch12-02-reading-a-file.html Example of how to compile and run the Rust program with command-line arguments. The first argument is a placeholder search term, and the second is the path to the file to be read. ```bash $ cargo run -- the poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep the poem.txt` Searching for the In file poem.txt With text: I'm nobody! Who are you? Are you nobody, too? Then there's a pair of us - don't tell! They'd banish us, you know. How dreary to be somebody! How public, like a frog To tell your name the livelong day To an admiring bog! ``` -------------------------------- ### Install Rust Nightly Toolchain Source: https://doc.rust-lang.org/book/appendix-07-nightly-rust.html Use this command to install the nightly release of Rust. This is required to use unstable features behind feature flags. ```bash $ rustup toolchain install nightly ``` -------------------------------- ### Open local Rust documentation Source: https://doc.rust-lang.org/book/ch01-01-installation.html This command opens the locally installed Rust documentation in your default web browser, allowing for offline access. ```bash rustup doc ``` -------------------------------- ### Expected Output for Arc/Mutex Example Source: https://doc.rust-lang.org/book/ch16-03-shared-state.html The expected output when the provided `Arc` and `Mutex` code snippet is executed. ```text Result: 10 ``` -------------------------------- ### Manual Trait Implementation Example Source: https://doc.rust-lang.org/book/ch20-05-macros.html This code shows how a user would manually implement the `HelloMacro` trait for a struct. This is the alternative to using a custom derive macro. ```Rust use hello_macro::HelloMacro; struct Pancakes; impl HelloMacro for Pancakes { fn hello_macro() { println!("Hello, Macro! My name is Pancakes!"); } } fn main() { Pancakes::hello_macro(); } ``` -------------------------------- ### Rust Doc-Tests Output Source: https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html Example output from running `cargo test` on documentation comments, showing that doc tests are executed and their results. ```text Doc-tests my_crate running 1 test test src/lib.rs - add_one (line 5) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s ``` -------------------------------- ### Example Test Output with tests/common.rs Source: https://doc.rust-lang.org/book/ch11-03-test-organization.html This output shows how `tests/common.rs` appears as a separate crate in test results, even without test functions. ```text __ $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished `test` profile [unoptimized + debuginfo] target(s) in 0.89s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test tests::internal ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running tests/common.rs (target/debug/deps/common-92948b65e88960b4) running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running tests/integration_test.rs (target/debug/deps/integration_test-92948b65e88960b4) running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` -------------------------------- ### Instantiate and Print a Public Struct in Rust Source: https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html This example demonstrates instantiating a public struct and printing it using `println!`. Ensure the struct derives `Debug` for printing. ```rust fn main() { let plant = Asparagus {}; println!("I'm growing {plant:?}"); } ``` -------------------------------- ### Example Panic Output Source: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html Illustrates the output when a `panic!` occurs due to an error, such as a file not being found. This output includes the error code, kind, and message. ```text $ cargo run Compiling error-handling v0.1.0 (file:///projects/error-handling) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.73s Running `target/debug/error-handling` thread 'main' panicked at src/main.rs:8:23: Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" } note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` -------------------------------- ### Pinning Futures for Vector Storage Source: https://doc.rust-lang.org/book/ch17-05-traits-for-async.html This example demonstrates pinning futures to allow them to be moved into a vector. This enables runtime modification of the futures collection before joining them. ```rust let futures: Vec>> = vec![tx1_fut, rx_fut, tx_fut]; trpl::join_all(futures).await; ``` -------------------------------- ### Importing `HashMap` from Standard Library Source: https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html Use the `use` keyword with an absolute path starting from `std` to bring items from the standard library, such as `HashMap`, into your package's scope. ```rust #[allow(unused)] fn main() { use std::collections::HashMap; } ``` -------------------------------- ### Check Cargo Installation Source: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html Verify if Cargo is installed on your system by checking its version. This command is essential before starting new Rust projects with Cargo. ```bash $ cargo --version ``` -------------------------------- ### Demonstrate Blog Post Workflow with State Pattern Source: https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html This example shows how to use the `Post` API to manage a blog post's lifecycle through different states (draft, review, published). It asserts that content is only available after approval. This code requires the `blog` crate to be implemented. ```Rust use blog::Post; fn main() { let mut post = Post::new(); post.add_text("I ate a salad for lunch today"); assert_eq!("", post.content()); post.request_review(); assert_eq!("", post.content()); post.approve(); assert_eq!("I ate a salad for lunch today", post.content()); } ``` -------------------------------- ### Rust Web Server Setup Source: https://doc.rust-lang.org/book/ch21-01-single-threaded.html Sets up a basic single-threaded TCP listener and iterates over incoming connections, passing each stream to the `handle_connection` function. This is the foundational structure for the web server. ```rust use std::fs; use std::io::{BufReader, prelude::*}; use std::net::{TcpListener, TcpStream}; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } // --snip-- fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); if request_line == "GET / HTTP/1.1" { let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); let response = format!( "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" ); stream.write_all(response.as_bytes()).unwrap(); } else { // some other request } } ``` -------------------------------- ### Get Value from HashMap Source: https://doc.rust-lang.org/book/ch08-03-hash-maps.html Retrieve a value from a hash map using the `get()` method with a reference to the key. `get()` returns an `Option<&V>`, which can be handled with methods like `copied()` and `unwrap_or()`. ```rust use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); let team_name = String::from("Blue"); let score = scores.get(&team_name).copied().unwrap_or(0); ``` -------------------------------- ### Crate-Level Documentation with //! Source: https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html Use `//!` doc comments at the beginning of `src/lib.rs` to document the entire crate. These comments appear on the crate's main documentation page. ```rust //! # My Crate //! //! `my_crate` is a collection of utilities to make performing certain //! calculations more convenient. /// Adds one to the number given. // --snip-- /// /// # Examples /// /// ``` /// let arg = 5; /// let answer = my_crate::add_one(arg); /// /// assert_eq!(6, answer); /// ``` pub fn add_one(x: i32) -> i32 { x + 1 } ``` -------------------------------- ### Access Vector Elements with Indexing and get Source: https://doc.rust-lang.org/book/ch08-01-vectors.html Demonstrates accessing the third element of a vector using both indexing (`v[2]`) and the `get` method (`v.get(2)`). Indexing panics on out-of-bounds access, while `get` returns an Option. ```rust fn main() { let v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {third}"); let third: Option<&i32> = v.get(2); match third { Some(third) => println!("The third element is {third}"), None => println!("There is no third element."), } } ``` -------------------------------- ### Update Rust installation Source: https://doc.rust-lang.org/book/ch01-01-installation.html Run this command in your shell to update your Rust installation to the latest stable version. ```bash $ rustup update ``` -------------------------------- ### Parsing Arguments and Initializing Config in Rust Source: https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html Sets up the main function to parse command-line arguments and build a configuration struct. Handles potential errors during argument parsing. ```Rust use std::env; use std::error::Error; use std::fs; use std::process; use minigrep::{search, search_case_insensitive}; // --snip-- fn main() { let args: Vec = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); if let Err(e) = run(config) { println!("Application error: {e}"); process::exit(1); } } pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { fn build(args: &[String]) -> Result { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } fn run(config: Config) -> Result<(), Box> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } ``` -------------------------------- ### Create New Rust Project Source: https://doc.rust-lang.org/book/ch21-01-single-threaded.html Use `cargo new` to create a new binary application project. Navigate into the project directory. ```bash $ cargo new hello Created binary (application) `hello` project $ cd hello ``` -------------------------------- ### Create Project Directory (Windows CMD) Source: https://doc.rust-lang.org/book/ch01-02-hello-world.html Use these commands to create and navigate into a new directory for your Rust project on Windows Command Prompt. ```batch > mkdir "%USERPROFILE%\projects" > cd /d "%USERPROFILE%\projects" > mkdir hello_world > cd hello_world ``` -------------------------------- ### Number Guessing Game Example Source: https://doc.rust-lang.org/book/ch20-03-advanced-types.html A complete example of the number guessing game, showcasing input handling, parsing, and comparison logic within a loop. ```rust use std::cmp::Ordering; use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); let mut guess = String::new(); // --snip-- io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {guess}"); // --snip-- match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } ``` -------------------------------- ### Integrate Library Crate into Main Binary Source: https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html Demonstrates how to use the `search` function from the `minigrep` library crate within the `src/main.rs` file. It includes argument parsing, error handling for configuration, and executing the search. ```rust use std::env; use std::error::Error; use std::fs; use std::process; // --snip-- use minigrep::search; fn main() { // --snip-- let args: Vec = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); if let Err(e) = run(config) { println!("Application error: {e}"); process::exit(1); } } // --snip-- struct Config { query: String, file_path: String, } impl Config { fn build(args: &[String]) -> Result { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } fn run(config: Config) -> Result<(), Box> { let contents = fs::read_to_string(config.file_path)?; for line in search(&config.query, &contents) { println!("{line}"); } Ok(()) } ``` -------------------------------- ### Define and Call Basic Functions in Rust Source: https://doc.rust-lang.org/book/ch03-03-how-functions-work.html Demonstrates defining and calling simple functions. Rust allows defining functions in any order as long as they are in a visible scope. ```rust fn main() { println!("Hello, world!"); another_function(); } fn another_function() { println!("Another function."); } ``` -------------------------------- ### Install C compiler on macOS Source: https://doc.rust-lang.org/book/ch01-01-installation.html If you encounter linker errors or need to compile Rust packages that depend on C code, install the Xcode command line tools on macOS. ```bash $ xcode-select --install ``` -------------------------------- ### Handle Out-of-Bounds Vector Access Source: https://doc.rust-lang.org/book/ch08-01-vectors.html Illustrates the behavior of indexing and the `get` method when accessing an index (100) that is out of bounds for a vector of five elements. Indexing panics, while `get` returns `None`. ```rust fn main() { let v = vec![1, 2, 3, 4, 5]; let does_not_exist = &v[100]; let does_not_exist = v.get(100); } ``` -------------------------------- ### Race Two Futures with `trpl::select` Source: https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html Use `trpl::select` to run two futures concurrently and get the result of the one that finishes first. This is useful for scenarios where you want to get a response from the quickest source. ```Rust extern crate trpl; // required for mdbook test use trpl::{Either, Html}; fn main() { let args: Vec = std::env::args().collect(); trpl::block_on(async { let title_fut_1 = page_title(&args[1]); let title_fut_2 = page_title(&args[2]); let (url, maybe_title) = match trpl::select(title_fut_1, title_fut_2).await { Either::Left(left) => left, Either::Right(right) => right, }; println!("{url} returned first"); match maybe_title { Some(title) => println!("Its page title was: '{title}'"), None => println!("It had no title."), } }) } async fn page_title(url: &str) -> (&str, Option) { let response_text = trpl::get(url).await.text().await; let title = Html::parse(&response_text) .select_first("title") .map(|title| title.inner_html()); (url, title) } ``` -------------------------------- ### Trait Object Compilation Error Example Source: https://doc.rust-lang.org/book/ch18-02-trait-objects.html This example demonstrates a common compilation error when attempting to use a type that does not implement the required trait for a trait object. Ensure all types in a trait object collection implement the specified trait. ```rust __ $ cargo run Compiling gui v0.1.0 (file:///projects/gui) error[E0277]: the trait bound `String: Draw` is not satisfied --> src/main.rs:5:26 | 5 | components: vec![Box::new(String::from("Hi"))], | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String` | = help: the trait `Draw` is implemented for `Button` = note: required for the cast from `Box` to `Box` For more information about this error, try `rustc --explain E0277`. error: could not compile `gui` (bin "gui") due to 1 previous error ``` -------------------------------- ### Rust Closure Type Inference Example Source: https://doc.rust-lang.org/book/ch13-01-closures.html This example demonstrates how Rust infers closure types. The first call to `example_closure` with a `String` locks in the type for `x` and the closure's return type. Subsequent calls with different types, like an integer, will result in a type error. ```rust let example_closure = |x| x; let s = example_closure(String::from("hello")); let n = example_closure(5.to_string()); ``` -------------------------------- ### Create a new Rust project and add dependencies Source: https://doc.rust-lang.org/book/ch01-01-installation.html Use `cargo new` to create a new project, `cd` to enter the directory, and `cargo add` to include external crates. This caches the dependencies for offline use. ```bash $ cargo new get-dependencies $ cd get-dependencies $ cargo add rand@0.8.5 trpl@0.2.0 ``` -------------------------------- ### Monomorphized Option Example Source: https://doc.rust-lang.org/book/ch10-01-syntax.html Illustrates the compiler-generated, specialized versions of `Option` for `i32` and `f64` after monomorphization. ```rust enum Option_i32 { Some(i32), None, } enum Option_f64 { Some(f64), None, } fn main() { let integer = Option_i32::Some(5); let float = Option_f64::Some(5.0); } ``` -------------------------------- ### Blog Post Workflow with State Transitions Source: https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html Demonstrates a blog post workflow where state transitions are managed by methods that consume the current state and return a new state. This prevents invalid states by encoding the workflow into the type system. ```Rust use blog::Post; fn main() { let mut post = Post::new(); post.add_text("I ate a salad for lunch today"); let post = post.request_review(); let post = post.approve(); assert_eq!("I ate a salad for lunch today", post.content()); } ``` -------------------------------- ### Rust Main Application Structure Source: https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html This Rust code sets up the main application logic, including argument parsing, error handling, and calling the core `run` function. It demonstrates collecting command-line arguments and building a `Config` struct. ```rust use std::env; use std::error::Error; use std::fs; use std::process; use minigrep::{search, search_case_insensitive}; // --snip-- fn main() { let args: Vec = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); if let Err(e) = run(config) { println!("Application error: {e}"); process::exit(1); } } pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { fn build(args: &[String]) -> Result { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } fn run(config: Config) -> Result<(), Box> { ``` -------------------------------- ### Deref Coercion Example Source: https://doc.rust-lang.org/book/ch15-02-deref.html Demonstrates calling a function expecting `&str` with a `&MyBox` due to deref coercion. ```rust use std::ops::Deref; impl Deref for MyBox { type Target = T; fn deref(&self) -> &T { &self.0 } } struct MyBox(T); impl MyBox { fn new(x: T) -> MyBox { MyBox(x) } } fn hello(name: &str) { println!("Hello, {name}!"); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&m); } ``` -------------------------------- ### Using Re-exported Items from a Crate Source: https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html This example demonstrates how to use types and functions that have been re-exported from another crate using `pub use`. It shows importing `PrimaryColor` and `mix` directly from the `art` crate. ```rust use art::PrimaryColor; use art::mix; fn main() { // --snip-- let red = PrimaryColor::Red; let yellow = PrimaryColor::Yellow; mix(red, yellow); } ``` -------------------------------- ### Create Project Directory (Linux/macOS/PowerShell) Source: https://doc.rust-lang.org/book/ch01-02-hello-world.html Use these commands to create and navigate into a new directory for your Rust project on Linux, macOS, or Windows PowerShell. ```bash $ mkdir ~/projects $ cd ~/projects $ mkdir hello_world $ cd hello_world ``` -------------------------------- ### Running Specific Integration Tests with Cargo Source: https://doc.rust-lang.org/book/ch11-03-test-organization.html Demonstrates how to run tests from a specific integration test file using the `--test` flag with `cargo test`. ```text __ $ cargo test --test integration_test Compiling adder v0.1.0 (file:///projects/adder) Finished `test` profile [unoptimized + debuginfo] target(s) in 0.64s Running tests/integration_test.rs (target/debug/deps/integration_test-82e7799c1bc62298) running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` -------------------------------- ### Incorrect Match Guard Precedence Example Source: https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html Illustrates the alternative, incorrect interpretation of match guard precedence with multiple patterns. ```Rust 4 | 5 | (6 if y) => ... ``` -------------------------------- ### Infinite Loop Example Source: https://doc.rust-lang.org/book/ch20-03-advanced-types.html Demonstrates an infinite loop that prints a message repeatedly. This expression has the never type '!' because it never terminates. ```rust fn main() { print!("forever "); loop { print!("and ever "); } } ``` -------------------------------- ### Define and Call Functions with Parameters in Rust Source: https://doc.rust-lang.org/book/ch03-03-how-functions-work.html Illustrates how to define a function that accepts a parameter and how to pass an argument when calling it. Parameters require explicit type annotations. ```rust fn main() { another_function(5); } fn another_function(x: i32) { println!("The value of x is: {x}"); } ``` -------------------------------- ### Variable Scope Example Source: https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html Demonstrates the scope of a string literal variable. Variables are valid from declaration until the end of their current scope. ```rust #![allow(unused)] fn main() { let s = "hello"; } ``` -------------------------------- ### Sample HTML File for Response Source: https://doc.rust-lang.org/book/ch21-01-single-threaded.html A basic HTML5 document structure. This file is read by the Rust server and sent as the response body. ```html Hello!

Hello!

Hi from Rust

``` -------------------------------- ### Declare an Array of Month Names Source: https://doc.rust-lang.org/book/ch03-02-data-types.html Example of declaring an array to hold a fixed collection of string literals, such as month names. ```rust #![allow(unused)] fn main() { let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; } ``` -------------------------------- ### Build Project with New Dependency Source: https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html Run 'cargo build' after adding a new dependency. Cargo will update the registry, download the specified crate and its dependencies, and then compile them along with your project. ```bash $ cargo build Updating crates.io index Locking 15 packages to latest Rust 1.85.0 compatible versions Adding rand v0.8.5 (available: v0.9.0) Compiling proc-macro2 v1.0.93 Compiling unicode-ident v1.0.17 Compiling libc v0.2.170 Compiling cfg-if v1.0.0 Compiling byteorder v1.5.0 Compiling getrandom v0.2.15 Compiling rand_core v0.6.4 Compiling quote v1.0.38 Compiling syn v2.0.98 Compiling zerocopy-derive v0.7.35 Compiling zerocopy v0.7.35 Compiling ppv-lite86 v0.2.20 Compiling rand_chacha v0.3.1 Compiling rand v0.8.5 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.48s ``` -------------------------------- ### Initial ThreadPool Struct Definition Source: https://doc.rust-lang.org/book/ch21-02-multithreaded.html Defines the simplest possible `ThreadPool` struct. This is a starting point for implementing thread pool functionality. ```rust pub struct ThreadPool; ``` -------------------------------- ### Absolute Paths Source: https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html Absolute paths start from the crate root, indicated by `crate` for the current crate or the crate name for external crates. ```rust use crate::front_of_house::hosting; fn main() { hosting::add_to_waitlist(); } ``` -------------------------------- ### Compile and Run (Windows) Source: https://doc.rust-lang.org/book/ch01-02-hello-world.html Compile your Rust source file and then run the executable on Windows. ```batch > rustc main.rs > .\main Hello, world! ``` -------------------------------- ### Web Server with ThreadPool Integration Source: https://doc.rust-lang.org/book/ch21-02-multithreaded.html Sets up a TCP listener and uses a `ThreadPool` to execute connection handling. Requires `ThreadPool::new` and `ThreadPool::execute` to be implemented. ```rust use hello::ThreadPool; use std::fs; use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::thread; use std::time::Duration; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming() { let stream = stream.unwrap(); pool.execute(|| { handle_connection(stream); }); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = match &request_line[..] { "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), "GET /sleep HTTP/1.1" => { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), }; let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); } ``` -------------------------------- ### String Slices: Slicing the Entire String Source: https://doc.rust-lang.org/book/ch04-03-slices.html Demonstrates creating a slice that references the entire string by omitting both start and end indices. ```rust fn main() { let s = String::from("hello"); let len = s.len(); let slice = &s[0..len]; let slice = &s[..]; } ``` -------------------------------- ### Cargo Run Output Source: https://doc.rust-lang.org/book/ch21-02-multithreaded.html Example output from running the multithreaded Rust program, showing worker threads picking up and executing jobs. ```bash $ cargo run Compiling hello v0.1.0 (file:///projects/hello) warning: field `workers` is never read --> src/lib.rs:7:5 | 6 | pub struct ThreadPool { | ---------- field in this struct 7 | workers: Vec, | ^^^^^^^ | = note: `#[warn(dead_code)]` on by default warning: fields `id` and `thread` are never read --> src/lib.rs:48:5 | 47 | struct Worker { | ------ fields in this struct 48 | id: usize, | ^^ 49 | thread: thread::JoinHandle<()>, | ^^^^^^ warning: `hello` (lib) generated 2 warnings Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.91s Running `target/debug/hello` Worker 0 got a job; executing. Worker 2 got a job; executing. Worker 1 got a job; executing. Worker 3 got a job; executing. Worker 0 got a job; executing. Worker 2 got a job; executing. Worker 1 got a job; executing. Worker 3 got a job; executing. Worker 0 got a job; executing. Worker 2 got a job; executing. ``` -------------------------------- ### Declare Character Values in Rust Source: https://doc.rust-lang.org/book/ch03-02-data-types.html Provides examples of declaring character variables using single quotes, including Unicode characters. ```rust fn main() { let c = 'z'; let z: char = 'ℤ'; // with explicit type annotation let heart_eyed_cat = '😻'; } ```