### Install Rust on Linux/MacOS Source: https://jasonwalton.ca/rust-book-abridged/ch01-getting-started Installs Rust using a script from rustup.rs and installs Xcode command line tools for macOS. ```shell curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh xcode-select --install ``` -------------------------------- ### Create and Run a Cargo Project Source: https://jasonwalton.ca/rust-book-abridged/ch01-getting-started Uses Cargo to create a new Rust project, navigate into it, and then build and run it. ```shell $ cargo new hello_cargo $ cd hello_cargo $ cargo build $ ./target/debug/hello_cargo $ cargo run ``` -------------------------------- ### Verify and Update Rust Installation Source: https://jasonwalton.ca/rust-book-abridged/ch01-getting-started Commands to check the installed Rust version and update it to the latest. ```shell rustc --version rustup update ``` -------------------------------- ### Rust 'Hello, World!' Program Source: https://jasonwalton.ca/rust-book-abridged/ch01-getting-started A basic Rust program that prints 'Hello, world!' to the console using the println! macro. ```rust fn main() { println!("Hello, world!"); } ``` -------------------------------- ### Compile and Run Rust Program Source: https://jasonwalton.ca/rust-book-abridged/ch01-getting-started Compiles a Rust source file using rustc and then executes the compiled program. ```shell $ rustc main.rs $ ./main Hello, world! ``` -------------------------------- ### Cargo Project Management Commands Source: https://jasonwalton.ca/rust-book-abridged/ch01-getting-started Demonstrates commands for checking a Cargo project without building an executable and building a release version. ```shell cargo check cargo build --release ``` -------------------------------- ### Install Binary Crate with cargo install Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo Installs a binary crate from crates.io using the `cargo install` command. The binary is typically placed in `~/.cargo/bin` and may require adding this directory to your system's PATH. ```bash $ cargo install ripgrep ``` -------------------------------- ### Create Rust Project and Navigate Source: https://jasonwalton.ca/rust-book-abridged/ch02-guessing-game Commands to create a new Rust project using Cargo and navigate into the project directory. Assumes Cargo is installed. ```bash $ cargo new guessing_game $ cd guessing_game ``` -------------------------------- ### Create and navigate Rust project Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Demonstrates the initial steps for starting a new Rust project using Cargo, including creating a new project and changing the directory. ```bash cargo new minigrep cd minigrep ``` -------------------------------- ### HTTP Request Example Source: https://jasonwalton.ca/rust-book-abridged/ch20/ch20-01-single-threaded-web-server Illustrates the structure of an incoming HTTP GET request, including the request line and headers. The request line follows the format 'Method Request-URI HTTP-Version CRLF'. ```http GET /index.html HTTP/1.1 Host: example.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive ``` -------------------------------- ### Rust String Slicing with Ranges Source: https://jasonwalton.ca/rust-book-abridged/ch04-ownership Demonstrates creating string slices using inclusive-to-exclusive range syntax (`[start..end]`) and shorthand notations to specify the start or end of the slice. ```rust let s = String::from("hello world"); let hello = &s[0..5]; // Type of `hello` is `&str`. let world = &s[6..11]; ``` ```rust let s = String::from("rust time"); let rust = &s[..4]; let time = &s[5..]; let rust_time = &s[..]; ``` -------------------------------- ### Rust - Integration Test Setup and Execution Source: https://jasonwalton.ca/rust-book-abridged/ch11-automated-tests Illustrates setting up integration tests in a `tests` directory and accessing the library's public API. Shows how to run specific integration tests by file name. ```directory adder ├── Cargo.lock ├── Cargo.toml ├── src │ └── lib.rs └── tests └── integration_test.rs ``` ```rust use adder; #[test] fn it_adds_two() { assert_eq!(4, adder::add_two(2)); } ``` ```bash # Run all tests, including integration tests $ cargo test # Run tests in a single file (e.g., integration_test.rs) $ cargo test --test integration_test ``` -------------------------------- ### Rust Path Syntax Examples Source: https://jasonwalton.ca/rust-book-abridged/zz-appendix/appendix-02-operators Demonstrates various ways to specify paths in Rust, including namespace paths, paths relative to the crate root or current module, and paths for associated items and methods. ```Rust ident::ident ::path self::path super::path type::ident ::ident ::... trait::method(...) type::method(...) ::method(...) ``` -------------------------------- ### Rust Tuple Syntax Examples Source: https://jasonwalton.ca/rust-book-abridged/zz-appendix/appendix-02-operators Demonstrates the syntax for working with tuples in Rust, including empty tuples, single-element tuples, tuple expressions, tuple types, tuple struct initialization, and tuple indexing. ```Rust () (expr) (expr,) (type,) (expr, ...) (type, ...) expr(expr, ...) expr.0 expr.1 ``` -------------------------------- ### Function-like Macro Usage Example (Rust) Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros An example of calling a function-like macro named 'sql'. This macro appears to process SQL queries. ```Rust let sql = sql!(SELECT * FROM posts WHERE id=1); ``` -------------------------------- ### Install Custom Cargo Command (cargo-audit) Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo Installs a custom cargo command, such as `cargo-audit`, which checks dependencies against security advisories. After installation, the command can be invoked directly using `cargo `. ```bash $ cargo install cargo-audit ``` ```bash $ cargo audit ``` -------------------------------- ### Rust Documentation Comment for Function (Rust) Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo Example of a documentation comment using triple slashes (///) in Rust, which supports Markdown and is used for generating documentation. Includes an example section that is also tested. ```rust /// Adds one to the number given. /// /// # Examples /// /// ``` /// let arg = 5; /// let answer = my_crate::add_one(arg); /// /// assert_eq!(6, answer); /// ``` pub fn add_one(x: i32) -> i32 { x + 1 } ``` -------------------------------- ### Rust Tests with `panic!` for Failure Source: https://jasonwalton.ca/rust-book-abridged/ch11-automated-tests An example demonstrating how to write multiple tests within a module, including one that intentionally fails using the `panic!` macro. ```rust #[cfg(test)] mod tests { #[test] fn exploration() { assert_eq!(2 + 2, 4); } #[test] fn another() { panic!("Sad trombone"); } } ``` -------------------------------- ### Rust Example Usage with Custom Component Source: https://jasonwalton.ca/rust-book-abridged/ch17-object-oriented-features Demonstrates how to use the `gui` library by defining a custom `SelectBox` component that implements the `Draw` trait and creating a `Screen` instance containing both a `SelectBox` and a `Button`. ```rust use gui::{Button, Screen}; // Define a custom SelectBox component, not // in the gui library. struct SelectBox { width: u32, height: u32, options: Vec, } impl Draw for SelectBox { fn draw(&self) { // code to actually draw a select box } } fn main() { let screen = Screen { components: vec![ Box::new(SelectBox { width: 75, height: 10, options: vec![ String::from("Yes"), String::from("Maybe"), String::from("No"), ], }), Box::new(Button { width: 50, height: 10, label: String::from("OK"), }), ], }; screen.run(); } ``` -------------------------------- ### Attribute-like Macro Usage Example (Rust) Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros An example of applying a custom attribute-like macro named 'route' to a Rust function. This macro likely handles routing for web requests. ```Rust #[route(GET, "/")] fn index() { } ``` -------------------------------- ### Rust: `Cargo.toml` Dependency Example Source: https://jasonwalton.ca/rust-book-abridged/ch02-guessing-game Illustrates how a crate dependency, like `rand`, is declared in the `Cargo.toml` file using semantic versioning. ```toml [dependencies] rand = "0.8.5" ``` -------------------------------- ### HTTP Response Example Source: https://jasonwalton.ca/rust-book-abridged/ch20/ch20-01-single-threaded-web-server Shows the format of an HTTP response, including the status line, headers, and body. The status line includes 'HTTP-Version Status-Code Reason-Phrase CRLF'. ```http HTTP/1.1 200 OK Content-Type: text Content-Length: 26 Hello, World! ``` -------------------------------- ### Manual Deref Coercion Example Source: https://jasonwalton.ca/rust-book-abridged/ch15-smart-pointers Shows the manual conversion process that would be required without deref coercion, involving dereferencing and slicing. ```rust fn main() { let m = MyBox::new(String::from("Rust")); hello(&(*m)[..]); } ``` -------------------------------- ### Create Rust Projects for Derive Macro Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros Initializes two Rust libraries, `hello_macro` for the trait and `hello_macro_derive` for the procedural macro, within a nested directory structure. This setup is typical for tightly coupled crates. ```bash mkdir projects cd projects cargo new hello_macro --lib cd hello_macro cargo new hello_macro_derive --lib ``` -------------------------------- ### Rust Tuple Type Examples Source: https://jasonwalton.ca/rust-book-abridged/ch03-common-programming-concepts Shows how to create, destructure, and access elements of a tuple in Rust. Tuples are fixed-size compound types that can group values of different types. ```rust let tup: (i32, f64, u8) = (800, 6.4, 1); // Destructuring assignment let (x, y, z) = tup; // Access individual elements let a = tup.0; let b = tup.1; let c = tup.2; ``` -------------------------------- ### while let Conditional Loops in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch18-patterns-and-matching Illustrates the `while let` loop construct, which continues as long as a pattern matches a value. This example pops elements from a stack until it's empty. ```rust let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); // This prints 3, 2, then 1. When `pop` // returns `None`, this loop will stop. while let Some(top) = stack.pop() { println!("{}", top); } ``` -------------------------------- ### Handling file opening errors using Result and match in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch09-error-handling Provides an example of opening a file in Rust and handling potential errors using the `Result` enum and a `match` expression. If an error occurs, it panics with a descriptive message. ```rust use std::fs::File; fn main() { let greeting_file_result = File::open("hello.txt"); let greeting_file = match greeting_file_result { Ok(file_obj) => file_obj, Err(error) => panic!("Problem opening the file: {:?}", error), }; } ``` -------------------------------- ### Rust Generics Syntax Examples Source: https://jasonwalton.ca/rust-book-abridged/zz-appendix/appendix-02-operators Illustrates the syntax for using generics in Rust, including specifying generic parameters for types, functions, structures, enums, and implementations, as well as defining higher-ranked lifetime bounds and associated types. ```Rust path<...> path::<...> method::<...> fn ident<...> ... struct ident<...> ... enum ident<...> ... impl<...> ... for<...> type type ``` -------------------------------- ### Rust HashMap Basic Operations and Ownership Source: https://jasonwalton.ca/rust-book-abridged/ch08-common-collections Illustrates the basic usage of `HashMap` in Rust, including creating, inserting values, retrieving values using `get`, and iterating over key-value pairs. It also explains how `HashMap` takes ownership of its keys and values. ```rust use std::collections::HashMap; fn main() { let mut scores = HashMap::new(); // Insert some values into the map scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); // Access values with `get` let team_name = String::from("Blue"); let score = scores.get(&team_name).copied().unwrap_or(0); // Iterate over the keys with a for loop: for (key, value) in &scores { println!("{key}: {value}"); } } ``` ```rust use std::collections::HashMap; let field_name = String::from("Favorite color"); let field_value = String::from("Blue"); let mut map = HashMap::new(); map.insert(field_name, field_value); // field_name and field_value are invalid at this point // as they have been moved. ``` -------------------------------- ### Declare a simple macro with macro_rules! Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros This example demonstrates how to declare a basic macro named `four!` using `macro_rules!`. It takes no arguments and expands to the expression `1 + 3`. Macros must be brought into scope or defined locally before use. ```rust macro_rules! four { () => { 1 + 3 }; } fn main() { let x = four!(); println!("{x}"); } ``` -------------------------------- ### Cargo: Controlling Test Execution Source: https://jasonwalton.ca/rust-book-abridged/ch11-automated-tests Provides examples of how to control the execution of Rust tests using `cargo test` arguments. It shows how to pass arguments to cargo itself versus the test runner using the `--` separator. ```shell $ cargo test --help ``` ```shell $ cargo test -- --help ``` -------------------------------- ### Conditional if let Expressions in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch18-patterns-and-matching Shows how `if let` uses patterns for conditional execution, similar to `match` but not requiring exhaustiveness. This example uses multiple `if let` and `else if` clauses to determine a background color based on different optional and result values. ```rust fn main() { let favorite_color: Option<&str> = None; let is_tuesday = false; let age: Result = "34".parse(); if let Some(color) = favorite_color { println!("Using your favorite color, {color}, as the background"); } else if is_tuesday { println!("Tuesday is green day!"); } else if let Ok(age) = age { if age > 30 { println!("Using purple as the background color"); } else { println!("Using orange as the background color"); } } else { println!("Using blue as the background color"); } } ``` -------------------------------- ### Implement a simplified vec! macro for vector creation Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros This example shows a simplified version of the standard `vec!` macro. It uses `#[macro_export]` to make the macro available outside its crate. The macro employs repetition (`$( $x:expr ),*`) to handle a variable number of comma-separated expressions, pushing each into a new vector. ```rust #[macro_export] macro_rules! vec { ( $( $x:expr ),* ) => { { let mut temp_vec = Vec::new(); $( temp_vec.push($x); ) * temp_vec } }; } ``` -------------------------------- ### JavaScript fs.readFile Example Source: https://jasonwalton.ca/rust-book-abridged/ch16-fearless-concurrency Demonstrates asynchronous file reading in Node.js using `fs.readFile`. This function initiates a file read operation and invokes a callback once the data is available. The actual file I/O might occur on a separate thread managed by the OS, but the JavaScript code itself runs within a single-threaded event loop. ```javascript fs.readFile(filename, {encoding: "utf-8"}, cb) ``` -------------------------------- ### Create and Navigate Rust Library Project Source: https://jasonwalton.ca/rust-book-abridged/ch11-automated-tests Commands to create a new Rust library project named 'adder' and navigate into its directory. This sets up the basic structure for a Rust library. ```bash $ cargo new adder --lib $ cd adder ``` -------------------------------- ### Rust Iterator Demonstration with `next` Source: https://jasonwalton.ca/rust-book-abridged/ch13-functional-language-features Demonstrates the usage of the `next` method on a vector iterator. It shows how `next` sequentially returns `Some` containing references to elements and `None` when the iterator is depleted. The example also illustrates the need for a mutable iterator variable (`mut v1_iter`). ```rust #[test] fn iterator_demonstration() { let v1 = vec![1, 2, 3]; let mut v1_iter = v1.iter(); assert_eq!(v1_iter.next(), Some(&1)); assert_eq!(v1_iter.next(), Some(&2)); assert_eq!(v1_iter.next(), Some(&3)); assert_eq!(v1_iter.next(), None); } ``` -------------------------------- ### Basic grep command usage Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Illustrates the fundamental command-line syntax for the `grep` utility, specifying a pattern and a filename. ```bash $ grep [pattern] [filename] ``` -------------------------------- ### Rust: Assert Equality and Inequality with assert_eq! and assert_ne! Source: https://jasonwalton.ca/rust-book-abridged/ch11-automated-tests Demonstrates using assert_eq! to check for equality and assert_ne! to check for inequality between two values. The values must implement the Debug and PartialEq traits. The example defines a Rectangle struct and tests inequality between two instances. ```rust #[derive(PartialEq, Debug)] struct Rectangle { width: u32, height: u32, } #[cfg(test)] mod tests { use super::*; #[test] fn larger_can_hold_smaller() { let larger = Rectangle { width: 8, height: 7 }; let smaller = Rectangle { width: 2, height: 2 }; // These rectangles are not "equal". assert_ne!(larger, smaller); } } ``` -------------------------------- ### Iterator Laziness Example in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch13-functional-language-features Shows the lazy nature of Rust iterators. Creating an iterator with `v1.iter()` does not perform any action until the iterator is consumed, for example, in a `for` loop. ```rust let v1 = vec![1, 2, 3]; // Create an iterator let v1_iter = v1.iter(); // Do something for each item the iterator returns. // The iterator doesn't do anything until we use it. for val in v1_iter { println!("Got: {}", val); } ``` -------------------------------- ### Create and Initialize Rust Workspace Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo This snippet demonstrates the initial steps to create a new directory for a Rust workspace, initialize it as a Git repository, and set up a .gitignore file to exclude the target directory. ```shell mkdir add cd add git init . echo "/target" > .gitignore ``` -------------------------------- ### Access Vector elements in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch08-common-collections Demonstrates accessing vector elements using index-based access (`[]`) and the `get` method. Index-based access panics on out-of-bounds access, while `get` returns an `Option`. ```Rust let v = vec![1, 2, 3, 4, 5]; let third = &v[2]; let fourth = v.get(3); ``` -------------------------------- ### Rust Cargo Project Creation Source: https://jasonwalton.ca/rust-book-abridged/ch20/ch20-01-single-threaded-web-server Commands to create a new Rust project using Cargo and navigate into the project directory. ```bash $ cargo new hello $ cd hello ``` -------------------------------- ### Running a Rust program with arguments Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Illustrates the command used to compile and run a Rust program, passing arguments through Cargo using the `--` separator. ```bash $ cargo run -- query file.txt ... Searching for query In file file.txt ``` -------------------------------- ### Rust: Get Last Char of First Line with Option '?' Source: https://jasonwalton.ca/rust-book-abridged/ch09-error-handling Demonstrates using the '?' operator with an Option to safely get the last character of the first line of a string. If any step returns None, the function immediately returns None. ```rust fn last_char_of_first_line(text: &str) -> Option { text.lines().next()?.chars().last() } ``` -------------------------------- ### Rust Config Struct and Build Function Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Defines a `Config` struct to hold query and file path, and a `build` associated function to construct it from command-line arguments. Handles insufficient arguments by returning an error. ```rust pub struct Config { pub query: String, pub file_path: String, } impl Config { pub 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 }) } } ``` -------------------------------- ### Rust Character Type Examples Source: https://jasonwalton.ca/rust-book-abridged/ch03-common-programming-concepts Illustrates the declaration of Rust's `char` type, which represents a four-byte Unicode scalar value. Examples include ASCII characters, Unicode symbols, and attempts to represent complex characters. ```rust let c = 'z'; let z: char = 'ℤ'; let heart_eyed_cat = '😻'; let space_woman_zwj = '👩🏻‍🚀'; // <== This doesn't work! ``` -------------------------------- ### Create Rust Project Source: https://jasonwalton.ca/rust-book-abridged/ch21-async Creates a new Rust project using Cargo for an asynchronous web server and navigates into the project directory. ```bash $ cargo new hello-async $ cd hello-async ``` -------------------------------- ### Rust: Accessing Module Items via Absolute and Relative Paths Source: https://jasonwalton.ca/rust-book-abridged/ch07-packages-crates-modules Illustrates how to call a function ('add_to_waitlist') from a nested module using both absolute paths (starting from `crate`) and relative paths (starting from the current module). It also highlights the necessity of using the `pub` keyword to make modules and functions accessible from outside their defining scope. ```rust mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } pub fn eat_at_restaurant() { // Absolute path crate::front_of_house::hosting::add_to_waitlist(); // Relative path, since this function is defined // the same modules as `front_of_house`. front_of_house::hosting::add_to_waitlist(); } ``` -------------------------------- ### Rust: Test for case-insensitive search Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Provides a unit test for the `search_case_insensitive` function, verifying its correctness with a case-insensitive query against sample text. ```rust #[cfg(test)] mod tests { use super::*; #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` -------------------------------- ### Rust Boolean Type Examples Source: https://jasonwalton.ca/rust-book-abridged/ch03-common-programming-concepts Demonstrates the declaration and assignment of boolean values in Rust. The `bool` type can hold either `true` or `false`. ```rust let t = true; let f: bool = false; ``` -------------------------------- ### HTML File Content (404) Source: https://jasonwalton.ca/rust-book-abridged/ch20/ch20-01-single-threaded-web-server Provides the HTML content for the 404 Not Found error page. ```html Hello!

Oops!

Sorry, I don't know what you're asking for.

``` -------------------------------- ### Rust: Post state transition with Option::take Source: https://jasonwalton.ca/rust-book-abridged/ch17-object-oriented-features Demonstrates how to transition a post's state using `Option::take` to handle ownership correctly when modifying the state field. ```rust pub fn request_review(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.request_review()) } } ``` -------------------------------- ### Rust: Dereferencing to Get Value Source: https://jasonwalton.ca/rust-book-abridged/ch04-ownership Explains and demonstrates the use of the dereference operator (`*`) in Rust to access the value a reference points to. ```rust let num1 = 7; // num1 has type `i32`. let num2 = &num1; // num2 has type `&i32`. let num3 = *num2; // num3 has type `i32` again. ``` -------------------------------- ### Create Rust Crates within Workspace Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo This section shows how to create individual binary and library crates within the root directory of the workspace using the `cargo new` command. ```shell cargo new adder cargo new add_one --lib cargo new add_two --lib ``` -------------------------------- ### Rust Main Function for Argument Parsing and Execution Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli The main function collects command-line arguments, builds a `Config` using `Config::build`, and executes the `run` function. It uses `unwrap_or_else` for error handling during argument parsing and `if let Err` for handling errors from the `run` function, printing errors to stderr. ```rust use minigrep::Config; use std::{env, process}; fn main() { let args: Vec = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {err}"); process::exit(1); }); if let Err(e) = minigrep::run(config) { eprintln!("Application error: {e}"); process::exit(1); } } ``` -------------------------------- ### for Loops with Destructuring in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch18-patterns-and-matching Demonstrates using patterns within `for` loops to destructure elements from an iterator. This example iterates over a vector and destructures each element into an index and a value. ```rust let v = vec!['a', 'b', 'c']; for (index, value) in v.iter().enumerate() { println!("{} is at index {}", value, index); } ``` -------------------------------- ### Windows PowerShell: Set environment variable for testing Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Demonstrates how to set the `IGNORE_CASE` environment variable using PowerShell on Windows for testing the case-insensitive search functionality. ```powershell PS> $Env:IGNORE_CASE=1 PS> cargo run -- to poem.txt PS> Remove-Item Env:IGNORE_CASE ``` -------------------------------- ### Handle Connections with Tokio Spawn Source: https://jasonwalton.ca/rust-book-abridged/ch21-async This code snippet shows how to accept incoming network connections using a Tokio listener and spawn a new asynchronous task to handle each connection. It emphasizes the use of an async block for idiomatic future creation and the `move` keyword for ownership transfer. ```rust loop { let (stream, _) = listener.accept().await.unwrap(); let f = handle_connection(stream); tokio::spawn(f); } ``` -------------------------------- ### Test Blog Post Workflow with State Transitions Source: https://jasonwalton.ca/rust-book-abridged/ch17-object-oriented-features A unit test demonstrating the complete blog post workflow: creating a draft, adding text, requesting a review, approving the post, and asserting the content. This verifies the compile-time state enforcement. ```rust #[cfg(test)] mod tests { use super::*; #[test] fn post_workflow() { 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()); } } ``` -------------------------------- ### Error Propagation with the `?` Operator in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch09-error-handling This example simplifies error handling by using the `?` operator, which automatically propagates errors by returning early if an `Err` is encountered. It assumes the error types are compatible or convertible. ```rust use std::fs::File; use std::io::{self, Read}; fn read_username_from_file() -> Result { let mut username_file = File::open("hello.txt")?; let mut username = String::new(); username_file.read_to_string(&mut username)?; Ok(username) } ``` -------------------------------- ### HTML File Content Source: https://jasonwalton.ca/rust-book-abridged/ch20/ch20-01-single-threaded-web-server Provides the HTML content for the main page to be served by the web server. ```html Hello!

Hello!

Hi from Rust

``` -------------------------------- ### Rust Static Dispatch Example Source: https://jasonwalton.ca/rust-book-abridged/ch17-object-oriented-features Demonstrates static dispatch in Rust where the compiler knows the concrete type of a variable ('Button') at compile time, allowing it to directly call the appropriate 'draw' method. ```rust let button = Button { width: 50, height: 10, label: String::from("OK"), }; button.draw(); ``` -------------------------------- ### Publishing a Rust Crate with Cargo Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo Provides the command-line instruction to publish a Rust crate to crates.io. It also mentions that names are unique and that version bumping (following semantic versioning) is necessary for subsequent updates. ```bash $ cargo publish ``` -------------------------------- ### Spawn a new thread with `thread::spawn` in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch16-fearless-concurrency Demonstrates creating a new OS-level thread using `thread::spawn` and a closure. It also shows how to use `handle.join()` to wait for the spawned thread to complete, preventing premature program termination. ```rust use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); } ``` -------------------------------- ### Rust Trait for Polymorphism (Iterator Example) Source: https://jasonwalton.ca/rust-book-abridged/ch17-object-oriented-features Illustrates polymorphism in Rust using the `Iterator` trait. This allows different types implementing the `Iterator` trait to be used interchangeably in constructs like `for` loops. ```Rust let numbers = vec![1, 2, 3]; for num in numbers.iter() { println!("{}", num); } ``` -------------------------------- ### Read Username Async in Rust with Tokio Source: https://jasonwalton.ca/rust-book-abridged/ch21-async Reads a username from a file asynchronously using Rust's Tokio runtime. This function mimics the JavaScript example by using `tokio::fs::read_to_string` and the `?` operator for error handling. ```Rust use std::{error::Error}; use tokio::fs; async fn get_user_name() -> Result<(), Box> { let username = fs::read_to_string("./username.txt").await?; println!("Hello {username}"); Ok(()) } ``` -------------------------------- ### Rust: Match Literals Source: https://jasonwalton.ca/rust-book-abridged/ch18-patterns-and-matching Demonstrates matching integer literals in Rust using a `match` expression. It covers matching specific values and a catch-all case. ```rust let x = 1; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), _ => println!("anything"), } ``` -------------------------------- ### Rust: Using Raw Identifiers for Keywords Source: https://jasonwalton.ca/rust-book-abridged/zz-appendix/appendix-01-keywords Demonstrates how to use raw identifiers (prefixing with `r#`) to use reserved Rust keywords like `match` as function names, resolving compilation errors. ```rust fn match(needle: &str, haystack: &str) -> bool { haystack.contains(needle) } ``` ```rust fn r#match(needle: &str, haystack: &str) -> bool { haystack.contains(needle) } fn main() { assert!(r#match("foo", "foobar")); } ``` -------------------------------- ### MIT License Text Source: https://jasonwalton.ca/rust-book-abridged/zz-appendix/appendix-06-licenses This block contains the full text of the MIT license, a permissive free software license. It grants users the right to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, with the condition that the copyright notice and permission notice are included in all copies or substantial portions of the Software. ```plaintext Copyright (c) 2010 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -------------------------------- ### Unix/Linux Shell: Set environment variable for testing Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Shows the command-line syntax for setting the `IGNORE_CASE` environment variable in a Unix or Linux shell to test the case-insensitive search feature. ```bash $ IGNORE_CASE=1 cargo run -- to poem.txt ``` -------------------------------- ### Rust Annotated Closure Example Source: https://jasonwalton.ca/rust-book-abridged/ch13-functional-language-features Illustrates how to define and annotate a Rust closure with explicit parameter and return types. This closure simulates a time-consuming calculation and captures a `u32` value. ```rust let expensive_closure = |num: u32| -> u32 { println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); num }; ``` -------------------------------- ### Calling Associated Functions from Traits in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-02-advanced-traits Shows how to define and call an associated function (`baby_name`) from a trait (`Animal`) implemented by a struct (`Dog`). This example illustrates the basic syntax for associated functions within traits. ```rust trait Animal { fn baby_name() -> String; } struct Dog; impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } fn main() { println!("A baby dog is called a {}", Dog::baby_name()); } ``` -------------------------------- ### Configure `Cargo.toml` for Procedural Macro Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros Sets up the `Cargo.toml` file for the `hello_macro_derive` crate, marking it as a procedural macro using `proc-macro = true` and adding `syn` and `quote` as dependencies. ```toml [lib] proc-macro = true [dependencies] syn = "1.0" quote = "1.0" ``` -------------------------------- ### Create Consumer Project `pancakes` Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros Creates a new Rust project named `pancakes`. This project will utilize the custom derive macro defined in `hello_macro_derive`. ```bash cd .. cargo new pancakes ``` -------------------------------- ### Rust: Dangling Reference Example Source: https://jasonwalton.ca/rust-book-abridged/ch10/ch10-03-lifetimes This Rust code snippet demonstrates a common scenario where a reference points to data that has gone out of scope, leading to a dangling reference. The Rust compiler prevents this by using lifetimes. ```rust fn main() { let r; { let x = 5; r = &x; } println!("r: {}", r); } ``` -------------------------------- ### Handle File Opening Errors with unwrap_or_else in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch09-error-handling Shows an alternative to extensive match statements for handling Result types. This example uses `unwrap_or_else` to provide a closure that executes when an error occurs, allowing for concise error handling. ```rust use std::fs::File; use std::io::ErrorKind; fn main() { let greeting_file = File::open("hello.txt").unwrap_or_else(|error| { if error.kind() == ErrorKind::NotFound { File::create("hello.txt").unwrap_or_else(|error| { panic!("Problem creating the file: {:?}", error); }) } else { panic!("Problem opening the file: {:?}", error); } }); } ``` -------------------------------- ### Adding Metadata to a Rust Crate with Cargo.toml Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo Shows how to define essential metadata for a Rust crate in its `Cargo.toml` file, which is required for publishing to crates.io. This includes the crate's name, version, edition, a description, and a license identifier. ```toml [package] name = "my_awesome_colors" version = "0.1.0" edition = "2021" description = "A fancy awesome crate for generating colored text in the terminal." license = "MIT" ``` -------------------------------- ### Match Different File Opening Errors in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch09-error-handling Demonstrates how to handle different file opening errors using nested match statements. It specifically handles NotFound errors by attempting to create the file, and panics for any other error. ```rust use std::fs::File; use std::io::ErrorKind; fn main() { let greeting_file_result = File::open("hello.txt"); let greeting_file = match greeting_file_result { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(e) => panic!("Problem creating the file: {:?}", e), }, other_error => { panic!("Problem opening the file: {:?}", other_error); } }, }; } ``` -------------------------------- ### Configure Workspace Cargo.toml Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo This snippet illustrates the structure of the root `Cargo.toml` file for a workspace, which specifies the `members` (packages) included in the workspace. ```toml [workspace] members = [ "adder", "add_one", "add_two", ] ``` -------------------------------- ### Rust Comment Styles Source: https://jasonwalton.ca/rust-book-abridged/ch03-common-programming-concepts Demonstrates various ways to write comments in Rust, including single-line comments (`//`), multi-line block comments (`/* ... */`), and documentation comments (`///` and `//!`) which support Markdown and are used for generating documentation. ```rust // This is a comment. // Multi-line comments // generally are written this way. /* You can use this style of comment too. */ /// This is a doc comment for the "next thing", in /// this case for the `foo` function. Markdown is /// allowed here. See chapter 14 for more details. fn foo() {} mod bar { //! This is a doc comment for the "parent thing", //! in this case the "bar" module. } ``` -------------------------------- ### Rust Function Returning Opaque Type Source: https://jasonwalton.ca/rust-book-abridged/ch10/ch10-02-traits Returns a type that implements the `Summary` trait but hides its concrete type (`Tweet` in this example) from the caller. The concrete type is inferred by the compiler. Dependencies: `Summary` trait, `Tweet` struct. ```rust fn returns_summarizable() -> impl Summary { Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, } } ``` -------------------------------- ### Run Binary Crate in Rust Workspace Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo This command executes the binary crate ('adder') within the workspace. If multiple binary crates exist, it shows how to specify which one to run using `-p` or by changing the current directory. ```shell cargo run ``` -------------------------------- ### Rust: Count Word Occurrences with HashMap Source: https://jasonwalton.ca/rust-book-abridged/ch08-common-collections An example demonstrating how to count the occurrences of each word in a string using a Rust HashMap. It utilizes `entry().or_insert()` to initialize counts to 0 and then increments them, returning a mutable reference to the count. ```rust use std::collections::HashMap; fn main() { let text = "hello world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); *count += 1; } println!("{:?}", map); } ``` -------------------------------- ### Define Methods on a Rust Enum Source: https://jasonwalton.ca/rust-book-abridged/ch06-enums-and-pattern-matching Shows how to implement methods for a Rust enum using an `impl` block. The example defines a `call` method on the `Message` enum, which would typically use pattern matching internally. ```rust impl Message { fn call(&self) { // method body would be defined here } } let m = Message::Write(String::from("hello")); m.call(); ``` -------------------------------- ### Reading file content in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Demonstrates how to read the entire content of a file into a `String` using `std::fs::read_to_string`. It includes error handling with `.expect()` for cases where the file cannot be read. ```Rust use std::env; use std::fs; fn main() { // --snip-- println!("In file {}", file_path); let contents = fs::read_to_string(file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); } ``` -------------------------------- ### Parse command-line arguments in Rust Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Shows how to access and collect command-line arguments provided to a Rust program using the `std::env::args` function. It highlights collecting arguments into a `Vec` and accessing specific arguments by index. ```Rust use std::env; fn main() { let args: Vec = env::args().collect(); // &args[0] is the name of the binary // e.g. target/debug/minigrep let query = &args[1]; let file_path = &args[2]; println!("Searching for {}", query); println!("In file {}", file_path); } ``` -------------------------------- ### Create a macro to add one to an expression Source: https://jasonwalton.ca/rust-book-abridged/ch19/ch19-05-macros This macro, `add_one!`, showcases capturing an expression using a metavariable `$e:expr`. When called with an expression, it expands to that expression plus one. It's an example of how macros can process and transform code snippets. ```rust macro_rules! add_one { ($e:expr) => { $e + 1 }; } ``` -------------------------------- ### Rust Thread::spawn Signature Source: https://jasonwalton.ca/rust-book-abridged/ch20/ch20-02-multi-threaded-web-server Illustrates the signature of Rust's `thread::spawn` function, showing its generic parameters for the closure and its return type, `JoinHandle`. ```rust pub fn spawn(f: F) -> JoinHandle where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static, { // --snip-- } ``` -------------------------------- ### Rust: Immutable Closure Capture Example Source: https://jasonwalton.ca/rust-book-abridged/ch13-functional-language-features Demonstrates a Rust closure capturing a vector as an immutable reference. The original vector remains accessible and unchanged after the closure is defined and called, highlighting safe, read-only access. ```rust fn immutable_example() { let list = vec![1, 2, 3]; println!("Before defining closure: {:?}", list); // Here `list` is captured as an immutable reference. let only_borrows = || println!("From closure: {:?}", list); println!("Before calling closure: {:?}", list); only_borrows(); println!("After calling closure: {:?}", list); } ``` -------------------------------- ### Add External Package Dependency in Workspace Source: https://jasonwalton.ca/rust-book-abridged/ch14-more-about-cargo This `Cargo.toml` example shows how to add an external crate (e.g., 'rand') as a dependency to a specific package ('add_one') within the workspace. The single `Cargo.lock` file ensures version consistency across the workspace. ```toml [dependencies] rand = "0.8.5" ``` -------------------------------- ### Rust Run Function for File Processing Source: https://jasonwalton.ca/rust-book-abridged/ch12-io-project-cli Implements a `run` function that takes a `Config` struct, reads the file specified in the config, and returns a `Result`. Uses the `?` operator for error propagation from file operations. ```rust use std::{error::Error, fs}; pub fn run(config: Config) -> Result<(), Box> { let contents = fs::read_to_string(config.file_path)?; todo!("Implement me!"); Ok(()) } ```