### Update Rust Installation Source: https://www.rustfinity.com/learn/rust/getting-started/installation To update your Rust installation to the latest stable version, use the `rustup update` command. This command fetches and installs the newest toolchains and components. ```shell rustup update ``` -------------------------------- ### Install Rust on Linux/macOS with Rustup Source: https://www.rustfinity.com/learn/rust/getting-started/installation This command installs the Rust toolchain manager, Rustup, on Linux and macOS systems. Rustup allows you to manage different Rust versions and associated tools. The installation process is interactive and recommends default settings. ```shell curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Verify Rust Installation Source: https://www.rustfinity.com/learn/rust/getting-started/installation After installing Rust, you can verify the installation by checking the version of the Rust compiler, `rustc`. This command should output the installed Rust version if the installation was successful. ```shell rustc --version ``` -------------------------------- ### Uninstall Rust Source: https://www.rustfinity.com/learn/rust/getting-started/installation If you need to remove Rust from your system, the `rustup self uninstall` command will cleanly remove Rustup and all installed toolchains. ```shell rustup self uninstall ``` -------------------------------- ### Rust Expression vs. Statement Example Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Contrasts Rust expressions (which evaluate to a value) and statements (which perform an action but do not return a value). Includes examples of both. ```rust fn main() { println!("Hello, World!"); // Statement } fn main() { let x = 5; let y = 10; x + y // Expression } ``` -------------------------------- ### Rust Stack Operations Example Source: https://www.rustfinity.com/learn/rust/the-stack-and-the-heap Demonstrates how function calls and primitive data types are managed on the stack in Rust. This example shows a series of nested function calls, illustrating the LIFO (Last In First Out) principle of stack allocation and deallocation. ```rust fn main() { let result = do_math(3, 4); println!("Result: {}", result); } fn do_math(a: i32, b: i32) -> i32 { let sum = add(a, b); let difference = subtract(a, b); let product = multiply(a, b); let quotient = divide(a, b); sum + difference + product + quotient } fn add(a: i32, b: i32) -> i32 { a + b } fn subtract(a: i32, b: i32) -> i32 { a - b } fn multiply(a: i32, b: i32) -> i32 { a * b } fn divide(a: i32, b: i32) -> i32 { a / b } ``` -------------------------------- ### Rust String Slicing Example Source: https://www.rustfinity.com/learn/rust/ownership/strings-and-slices Demonstrates creating a String and then deriving slices from it to reference specific parts of the string. Slices are references to sequences of bytes within a String. ```Rust fn main() { let my_string = String::from("Hello, World!"); let hello = &my_string[0..5]; let world = &my_string[7..12]; println!("Hello, {}", world); } ``` -------------------------------- ### Rust 'Hello, World!' using Cargo Source: https://www.rustfinity.com/learn/rust/getting-started/hello-world This snippet demonstrates creating, compiling, and running the 'Hello, World!' program using Rust's package manager and build system, Cargo. It simplifies project setup and management. The `cargo new` command initializes the project structure, and `cargo run` handles compilation and execution. ```shell cargo new hello-world cd hello-world ``` ```rust fn main() { println!("Hello, World!"); } ``` ```shell cargo run ``` -------------------------------- ### Rust Single-line Comments Source: https://www.rustfinity.com/learn/rust/the-programming-basics/comments Demonstrates the use of single-line comments in Rust, which start with `//` and are ignored by the compiler. They can appear on their own line or after a line of code. ```rust fn main() { let x = 5; // This is a single-line comment } ``` ```rust fn main() { let x = 5; // This is a single-line comment } ``` -------------------------------- ### Rust String Slices and Ownership Rules Example Source: https://www.rustfinity.com/learn/rust/ownership/strings-and-slices This example illustrates Rust's ownership rules when using string slices. It shows a scenario where a function returns a string slice, and how modifying the original String might invalidate the slice if not handled carefully. The code highlights potential issues and the importance of relational linking between slices and their source data. ```rust fn main() { let mut text = String::from("good morning"); let prefix = get_prefix(&text); text = format!("Hello {}", text); println!("The prefix is: {}", prefix); println!("The text is: {}", text); } fn get_prefix(t: &String) -> &str { let characters = t.chars(); for (idx, char) in characters.enumerate() { if char == ' ' { return t[0..idx]; } } t[..] } ``` -------------------------------- ### Instantiating a Rust Struct (Bird) Source: https://www.rustfinity.com/learn/rust/structs/structs-and-ownership This code shows how to create an instance of the 'Bird' struct. It initializes the 'name' field with a String and the 'age' field with a u32. The example illustrates the basic usage of a struct. ```rust fn main() { let bird = Bird { name: String::from("Sparrow"), age: 2, }; } ``` -------------------------------- ### Rust Pure Function for SHA-256 Hashing Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions An example of a pure function in Rust that generates a SHA-256 hash for a given string input. This function is pure as it produces the same output for the same input and has no side effects. ```rust use sha256::digest; fn generate_sha_256_hash(input: &str) -> String { let hash = digest(input.as_bytes()); hash } ``` -------------------------------- ### Rust Infinite Loop with `loop` Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Demonstrates the basic `loop` construct in Rust, which executes code indefinitely until explicitly stopped with `break`. This is useful for scenarios requiring continuous operation. ```rust fn main() { loop { println!("Hello, World!"); } } ``` -------------------------------- ### Rust Declaring Multiple Constants Source: https://www.rustfinity.com/learn/rust/the-programming-basics/variables Provides an example of declaring multiple constants of different types (integer, float, string slice) in Rust. Demonstrates type annotations and human-readable number formatting. ```rust const MAX_POINTS: u32 = 100_000; const PI: f32 = 3.14; const AUTHOR: &str = "John Doe"; fn main() { println!("The value of MAX_POINTS is: {}", MAX_POINTS); println!("The value of PI is: {}", PI); println!("The author is: {}", AUTHOR); } ``` -------------------------------- ### Rust 'if let' for simple pattern matching Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/pattern-matching Shows how to use the 'if let' construct in Rust for simpler pattern matching scenarios. It's useful when you only need to execute code for a specific pattern and don't need to handle all possible cases, unlike the 'match' keyword. This example checks for a specific enum variant. ```rust enum State { Idle, Running, Waiting, } fn print_state(state: State) { if let State::Idle = state { println!("The system is idle"); } } fn main() { let state = State::Idle; print_state(state); } ``` -------------------------------- ### Rust `while` Loop Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Presents the `while` loop in Rust, which executes a block of code as long as a given boolean condition remains true. This is ideal for loops where the termination condition is known beforehand. ```rust fn main() { let mut counter = 0; while counter < 10 { println!("{}. Hello, World!", counter + 1); counter += 1; } } ``` -------------------------------- ### Rust `loop` with `continue` Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Demonstrates using the `continue` keyword within a Rust `loop` to skip the remainder of the current iteration and proceed to the next. This is useful for conditional skipping of loop body execution. ```rust fn main() { let mut counter = 0; loop { counter += 1; if counter % 2 == 0 { continue; } if counter > 9 { break; } println!("The number is: {}", counter); } } ``` -------------------------------- ### Iterate Over Array with For Loop in Rust Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Demonstrates how to iterate over an array of numbers using a for loop in Rust. It prints each element of the array to the console. This is a fundamental way to process collections in Rust. ```Rust fn main() { let numbers = [1, 2, 3, 4, 5]; for number in numbers.iter() { println!("The number is: {}", number); } } ``` -------------------------------- ### For Loop Over Inclusive Range in Rust Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Illustrates using a for loop with an inclusive range (including the end value) in Rust. This allows for iteration up to and including the specified upper bound. ```Rust fn main() { for number in 1..=5 { println!("The number is: {}", number); } } ``` -------------------------------- ### Rust 'match' with guards for conditional pattern matching Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/pattern-matching Illustrates advanced pattern matching in Rust using 'match' with guards. Guards add an extra condition to a pattern, allowing for more complex matching logic beyond simple value equality. This example shows matching a number against a range condition. ```rust fn main() { let x = 5; match x { 1 => println!("One"), 2 => println!("Two"), 3 => println!("Three"), n if n > 3 => println!("Greater than three"), _ => println!("Other"), } } ``` -------------------------------- ### Rust Nested Loops with Labels (`loop`) Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Explains and demonstrates the use of loop labels in Rust to break out of specific nested loops. Labels allow explicit control over which loop is terminated when `break` is encountered. ```rust fn main() { let mut outer_counter = 0; 'outer: loop { let mut inner_counter = 0; 'inner: loop { println!( "Outer loop: {}, Inner loop: {}", outer_counter, inner_counter ); if inner_counter == 5 { break 'inner; // Exits the inner loop } if outer_counter == 2 { break 'outer; // Exits the outer loop } inner_counter += 1; } outer_counter += 1; } } ``` -------------------------------- ### Rust Variable Shadowing Example Source: https://www.rustfinity.com/learn/rust/the-programming-basics/variables Demonstrates Rust's shadowing feature where a new variable can reuse a name, effectively hiding the previous one. The latest declaration is used in subsequent operations. ```rust fn main() { let x = 5; let x = x + 1; let x = x * 2; println!("The value of x is: {}", x); } ``` -------------------------------- ### Rust `loop` with `break` Condition Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Shows how to exit a `loop` in Rust using the `break` keyword when a specific condition is met. This prevents infinite execution and allows program termination based on defined criteria. ```rust fn main() { let mut counter = 0; loop { println!("{}. Hello, World!", counter + 1); counter += 1; if counter == 10 { break; } } } ``` -------------------------------- ### Rust: Multiple Immutable References Example Source: https://www.rustfinity.com/learn/rust/ownership/borrowing This Rust code demonstrates the correct usage of multiple immutable references to the same String. The Rust compiler allows multiple immutable references simultaneously because it guarantees that the value will not be modified, thus preventing data races and ensuring safety. ```rust fn main() { let s = String::from("hello"); let r1 = &s; let r2 = &s; println!("r1: {}, r2: {}", r1, r2); } ``` -------------------------------- ### For Loop Over a Range in Rust Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Shows how to use a for loop to iterate over a range of numbers (exclusive of the end value) in Rust. This is useful for executing a block of code a specific number of times. ```Rust fn main() { for number in 1..5 { println!("The number is: {}", number); } } ``` -------------------------------- ### Rust `loop` Returning a Value Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Illustrates how a `loop` in Rust can act as an expression, returning a value when the `break` keyword is used with an expression. This allows capturing the result of a loop's computation. ```rust fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; println!("The result is: {}", result); } ``` -------------------------------- ### Rust Variable Scope Example Source: https://www.rustfinity.com/learn/rust/the-programming-basics/variables Demonstrates how variables declared within inner blocks are accessible only within those blocks in Rust. When a variable goes out of scope, its memory is freed. ```rust fn main() { let x = 5; // x is valid from this point { let y = 10; // y is valid from this point println!("The value of y is: {}", y); } // y goes out of scope here println!("The value of x is: {}", x); } ``` -------------------------------- ### Rust Function with Side Effects (Writing to File) Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions An example of a Rust function that performs a side effect by writing data to a specified file. This function modifies external state (the file system), making its behavior harder to predict. ```rust fn write_to_file(data: &str, filename: &str) { let mut file = File::create(filename).expect("Failed to create file"); file.write_all(data.as_bytes()).expect("Failed to write to file"); } ``` -------------------------------- ### Rust If Else Error Example Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/if-expressions Highlights a common compile-time error in Rust when using if/else expressions in a `let` statement where the `if` and `else` blocks return values of different types. This enforces type safety. ```rust fn main() { let condition = true; let number = if condition { 10 } else { "hello" }; println!("The value of number is: {}", number); } ``` -------------------------------- ### Rust Type Inference and Annotation Example Source: https://www.rustfinity.com/learn/rust/the-programming-basics/data-types Demonstrates how Rust infers the type of a variable (`x` as i32) and how to explicitly annotate a variable's type (`y` as i64). This highlights Rust's static typing and its ability to infer types when possible. ```Rust fn main() { let x = 5; // Type is inferred as i32 let y: i64 = 10; // Rust will use the type i64 for y } ``` -------------------------------- ### Rust Variable Scope and Value Dropping Source: https://www.rustfinity.com/learn/rust/ownership/ownership-rules Demonstrates how variables in Rust have a defined scope. When a variable goes out of scope, its value is dropped, freeing up memory. This example shows nested scopes and when values are no longer valid. ```rust fn main() { let x = 5; // x is valid from this point { let y = 10; // y is valid from this point println!("The value of y is: {}", y); } // y goes out of scope here println!("The value of x is: {}", x); } ``` -------------------------------- ### Use Random Number Generator in Main Function Source: https://www.rustfinity.com/learn/rust/number-guessing-game This Rust code integrates the 'generate_random_number' function into the 'main' function. It calls the function to get a random number, stores it in the 'random_number' variable, and then prints this generated number to the console for verification. ```rust fn main() { println!("Number guessing game"); let random_number = generate_random_number(); println!("Random number: {}", random_number); } ``` -------------------------------- ### Attempt to Reassign Immutable Variable in Rust (Compile Error) Source: https://www.rustfinity.com/learn/rust/the-programming-basics/variables Shows an example where an attempt is made to reassign a value to an immutable variable 'x', resulting in a compile-time error. This highlights Rust's default immutability. ```rust fn main() { let x = 5; x = 10; // Should cause a compile error } ``` -------------------------------- ### Control Flow in Rust For Loops (Continue and Break) Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/loops Explains that 'continue' and 'break' statements can be used within Rust for loops, similar to other loop types. 'Continue' skips the current iteration, while 'break' exits the loop entirely. ```Rust // Example demonstrating continue and break would go here, but is not provided in the source text. // A placeholder comment indicating where such code might be placed. ``` -------------------------------- ### Rust: Multiple Mutable References Error Example Source: https://www.rustfinity.com/learn/rust/ownership/borrowing This Rust code attempts to create two mutable references to the same String and pass them to a function. This will result in a compile-time error due to Rust's rule of only allowing one mutable reference per value in a scope. The compiler prevents this to avoid potential data races. ```rust fn main() { let mut s = String::from("hello"); let r1 = &mut s; let r2 = &mut s; concatenate(r1, r2); } fn concatenate(s1: &mut String, s2: &mut String) -> String { let result = s1.to_string() + s2; result } ``` -------------------------------- ### Rust String Slice: Get Prefix Before Mutation Source: https://www.rustfinity.com/learn/rust/ownership/strings-and-slices This Rust code demonstrates how to create a string slice (`prefix`) referencing a portion of a mutable String (`text`). It highlights a common ownership error where a slice is used after the original string it references has been mutated, leading to a compile-time error. This prevents bugs by enforcing Rust's borrowing rules. ```rust fn get_prefix(t: &str) -> &str { for (idx, char) in t.chars().enumerate() { if char == ' ' { return &t[0..idx]; } } &t[..] } fn main() { let mut text = String::from("good morning"); let prefix: &str = get_prefix(&text); text = format!("Hello {}", text); println!("The prefix is: {}", prefix); println!("The text is: {}", text); } ``` -------------------------------- ### Rust Ownership Error: Using Field After Move Source: https://www.rustfinity.com/learn/rust/structs/structs-and-ownership This example intentionally attempts to use a struct field ('bird.name') after its ownership has been moved to another instance ('new_bird'). This results in a compile-time error, illustrating Rust's strict ownership rules. ```rust fn main() { let bird = Bird { name: String::from("Sparrow"), age: 2, }; let new_bird = Bird { name: bird.name, age: 3, }; println!("The new bird's name is {}", new_bird.name); println!("The old bird's name is {}", bird.name); } ``` -------------------------------- ### Rust Array Slice: Accessing Sub-array Elements Source: https://www.rustfinity.com/learn/rust/ownership/strings-and-slices This Rust code demonstrates how to create a slice from an array. A slice provides a view into a contiguous sequence of elements within the array without copying the data. This example shows accessing elements from index 1 up to (but not including) index 3. ```rust fn main() { let numbers = [1, 2, 3, 4, 5]; let slice = &numbers[1..3]; println!("Slice: {:?}", slice); } ``` -------------------------------- ### Create Multiple Rust Binaries using Cargo Source: https://www.rustfinity.com/learn/rust/getting-started/hello-world This snippet demonstrates the command-line steps to set up a new binary file within a Rust project's `src/bin` directory. It is a prerequisite for running multiple executables. ```shell mkdir src/bin touch src/bin/hello-world.rs ``` -------------------------------- ### Rust 'Hello, World!' using rustc Source: https://www.rustfinity.com/learn/rust/getting-started/hello-world This snippet shows the basic 'Hello, World!' program in Rust, compiled and run directly using the `rustc` compiler. It includes creating the project directory, the source file, compiling, and executing the program. This method is foundational but less common for larger projects. ```shell mkdir hello-world cd hello-world mkdir src touch src/main.rs ``` ```rust fn main() { println!("Hello, World!"); } ``` ```shell rustc src/main.rs ./main ``` -------------------------------- ### Run Specific Rust Binary using Cargo Source: https://www.rustfinity.com/learn/rust/getting-started/hello-world This snippet shows how to execute a specific binary file within a multi-binary Rust project using the `cargo run` command with the `--bin` flag. This allows targeting individual executables. ```shell cargo run --bin hello-world ``` -------------------------------- ### Define and Call a Simple Rust Function Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Demonstrates the basic syntax for defining a function named 'greet' in Rust and how to call it from the 'main' function. The 'greet' function prints 'Hello, World!' to the console. ```rust fn greet() { println!("Hello, World!"); } fn main() { greet(); } ``` -------------------------------- ### Navigate to Project Directory Source: https://www.rustfinity.com/learn/rust/number-guessing-game These commands navigate the terminal into the newly created project directory and then open the project in Visual Studio Code. This is a standard way to begin working on a Rust project after its initialization. ```bash cd number-guessing-game code . ``` -------------------------------- ### Create a Rust Struct Instance Source: https://www.rustfinity.com/learn/rust/structs/defining-and-using-structs Demonstrates how to create an instance of the 'User' struct defined previously. This involves providing values for each field during initialization. ```rust fn main() { let user = User { id: 1, username: String::from("john_doe"), email: String::from("jon@doe.com"), }; } ``` -------------------------------- ### Demonstrate Rust Book Struct Usage Source: https://www.rustfinity.com/learn/rust/structs/challenge Demonstrates the usage of the 'Book' struct and its associated functions and methods. It shows how to create book instances, borrow them, return them, and check their availability status. ```rust fn main() { let mut book1 = Book::new("1984", "George Orwell"); let mut book2 = Book::new("To Kill a Mockingbird", "Harper Lee"); println!("Is '{}' available? {}", book1.title, book1.is_available()); book1.borrow(); println!("Is '{}' available? {}", book1.title, book1.is_available()); book1.return_book(); println!("Is '{}' available? {}", book1.title, book1.is_available()); println!("Is '{}' available? {}", book2.title, book2.is_available()); book2.borrow(); println!("Is '{}' available? {}", book2.title, book2.is_available()); } ``` -------------------------------- ### Rust SHA-256 Hashing with Main Function Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions A complete Rust program demonstrating the `generate_sha_256_hash` pure function. It takes a sample input string, generates its SHA-256 hash, and prints the result. ```rust use sha256::digest; fn generate_sha_256_hash(input: &str) -> String { let hash = digest(input.as_bytes()); hash } fn main() { let input = "Hello, world!"; let hash = generate_sha_256_hash(input); println!("The SHA-256 hash of '{}' is: {}", input, hash); } ``` -------------------------------- ### Quiet Execution with Cargo in Rust Source: https://www.rustfinity.com/learn/rust/getting-started/hello-world This snippet illustrates how to run a Rust program managed by Cargo with reduced output. The `--quiet` or `-q` flag suppresses Cargo's build and execution logs, showing only the program's direct output. This is useful for cleaner terminal output during development or when integrating into scripts. ```shell cargo run --quiet ``` -------------------------------- ### Rust Struct Init Shorthand Source: https://www.rustfinity.com/learn/rust/structs/defining-and-using-structs Illustrates the struct init shorthand in Rust, where variable names match struct field names. This simplifies instance creation by omitting redundant field assignments. ```rust fn main() { let username = String::from("john_doe"); let email = String::from("jon@doe.com"); let user = User { id: 1, username, email }; } ``` -------------------------------- ### Create New Rust Project with Cargo Source: https://www.rustfinity.com/learn/rust/number-guessing-game This command initializes a new Rust project named 'number-guessing-game' using Cargo, Rust's build system and package manager. It sets up the basic project structure, including source files and configuration. ```bash cargo new number-guessing-game ``` -------------------------------- ### Basic Rust Program Structure Source: https://www.rustfinity.com/learn/rust/number-guessing-game This Rust code snippet demonstrates the basic structure of a 'main.rs' file. It includes importing the 'std::io' module for input/output operations and defines the 'main' function, which is the entry point of every Rust executable. It prints a simple greeting to the console. ```rust use std::io; fn main() { println!("Number guessing game"); } ``` -------------------------------- ### Rust Documentation Comments (rustdoc) Source: https://www.rustfinity.com/learn/rust/the-programming-basics/comments Shows how to write documentation comments in Rust using `///` for single-line and `/** */` for multi-line documentation. These are used by the `rustdoc` tool to generate project documentation. ```rust /// Takes 2 numbers as arguments and returns the sum /// of the 2 numbers fn add(x: i32, y: i32) -> i32 { x + y } ``` ```rust /** * Takes 2 numbers as arguments and returns the sum * of the 2 numbers */ fn add(x: i32, y: i32) -> i32 { x + y } ``` -------------------------------- ### Rust Function with Parameters Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Illustrates how to define and call a Rust function that accepts parameters. The 'add' function takes two i32 integers, calculates their sum, and prints the result. ```rust fn add(a: i32, b: i32) { let sum = a + b; println!("The sum of {} and {} is {}", a, b, sum); } fn main() { add(5, 3); } ``` -------------------------------- ### Rust 'match' keyword for basic pattern matching Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/pattern-matching Demonstrates the basic usage of the 'match' keyword in Rust to compare a variable's value against a series of patterns and execute corresponding code blocks. It handles specific values and a wildcard for unmatched cases. This is fundamental for conditional logic based on data. ```rust fn main() { let x = 5; match x { 1 => println!("One"), 2 => println!("Two"), 3 => println!("Three"), _ => println!("Other"), } } ``` -------------------------------- ### Passing Ownership Between Functions in Rust Source: https://www.rustfinity.com/learn/rust/ownership/borrowing Demonstrates how a function can take ownership of a String and return it, allowing the original owner to regain possession. This method can be less readable for complex scenarios. ```rust fn main(){ let s = String::from("Hello"); let s = takes_ownership(s); println!("s is {}", s); } fn takes_ownership(s: String) -> String { println!("s is {}", s); s } ``` -------------------------------- ### Storing Data on the Heap with Box in Rust Source: https://www.rustfinity.com/learn/rust/the-stack-and-the-heap Demonstrates how to allocate memory on the heap for a scalar type using the `Box` smart pointer. This allows data to grow or shrink at runtime. The `println!` macro then accesses the data through the pointer. ```rust fn main() { let x = Box::new(5); println!("x = {}", x); } ``` -------------------------------- ### Creating and Printing a Rust Tuple Source: https://www.rustfinity.com/learn/rust/the-programming-basics/data-types Shows how to define a tuple in Rust with elements of different types and how to print its contents using the debug formatter. ```rust fn main() { let tup: (i32, f64, u8) = (999, 3.14, 1); println!("The value of tup is: {:?}", tup); } ``` -------------------------------- ### Rust: Using Dragon methods in `main` Source: https://www.rustfinity.com/learn/rust/structs/implementing-methods Demonstrates the usage of defined methods (`attack` and `level_up`) on a `Dragon` instance named `mushu`. It shows how to create a mutable instance and call its methods. ```rust fn main() { let mut mushu = Dragon { name: "Mushu".to_string(), level: 1, fire_power: 10, }; println!("{:?}", mushu); mushu.attack(); mushu.attack(); mushu.level_up(); println!("{:?}", mushu); } ``` -------------------------------- ### Rust 'Cargo.toml' with Dependency Source: https://www.rustfinity.com/learn/rust/number-guessing-game This snippet shows the 'Cargo.toml' file after the 'rand' crate has been added. It lists the project's metadata and specifies 'rand' with version '0.8.5' under the '[dependencies]' section, indicating it's required for the project. ```toml [package] name = "number-guessing-game" version = "0.1.0" edition = "2021" [dependencies] rand = "0.8.5" ``` -------------------------------- ### Implement Rust Book Struct 'return_book()' Method Source: https://www.rustfinity.com/learn/rust/structs/challenge Implements the 'return_book()' method for the 'Book' struct. This method mutates the 'available' field back to 'true', signifying the book has been returned. ```rust impl Book { fn return_book(&mut self) { self.available = true; } } ``` -------------------------------- ### Define Rust Book Struct Source: https://www.rustfinity.com/learn/rust/structs/challenge Defines the basic structure for a 'Book' with title, author, and availability status. This serves as the foundation for all subsequent operations. ```rust struct Book { title: String, author: String, available: bool, } ``` -------------------------------- ### Rust Struct Update Syntax Source: https://www.rustfinity.com/learn/rust/structs/defining-and-using-structs Explains and demonstrates the struct update syntax in Rust. This feature allows creating a new struct instance by copying values from an existing instance, modifying only specified fields. ```rust fn main() { let user1 = User { id: 1, username: String::from("john_doe"), email: String::from("jon@doe.com"), }; let user2 = User { id: 2, ..user1 }; } ``` -------------------------------- ### Number Guessing Game Loop in Rust Source: https://www.rustfinity.com/learn/rust/number-guessing-game Sets up the main loop for a number guessing game in Rust. It initializes a random number (assuming `generate_random_number()` exists) and continuously prompts the user for input, compares the guess, and prints the result until the program is terminated. ```rust fn main() { println!("Number guessing game"); // Assuming generate_random_number() is defined elsewhere // let random_number = generate_random_number(); let random_number = 50; // Placeholder for example loop { let user_input = read_user_input(); // Assumes read_user_input() is defined let text = compare_numbers(user_input, random_number); // Assumes compare_numbers() is defined println!("{}", text); } } ``` -------------------------------- ### Implement Rust Book Struct 'new()' Associated Function Source: https://www.rustfinity.com/learn/rust/structs/challenge Implements an associated function 'new()' for the 'Book' struct. This function acts as a constructor, creating a new book instance with provided title and author, and defaulting 'available' to true. ```rust impl Book { fn new(title: &str, author: &str) -> Self { Self { title: title.to_string(), author: author.to_string(), available: true, } } } ``` -------------------------------- ### Rust Directly Using Returned Function Value Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Demonstrates another way to use a Rust function's returned value by passing it directly as an argument to another function, such as `println!`. ```rust fn main() { println!("The sum of 5 and 3 is {}", add(5, 3)); } ``` -------------------------------- ### Rust Block Expression for Return Value Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Shows how to use a block expression in Rust to create a scope and return a value. The last expression in the block becomes the value of the block, which can be assigned to a variable. ```rust fn main() { let x = { let y = 5; y + 1 // This expression will be the value of `x` }; println!("The value of x is: {}", x); } ``` -------------------------------- ### Rust Using Returned Function Value Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Shows how to utilize the value returned by a Rust function. The returned sum from the `add` function is assigned to a variable `result` and then printed. ```rust fn main() { let result = add(5, 3); println!("The sum of 5 and 3 is {}", result); } ``` -------------------------------- ### Access Fields of a Rust Struct Instance Source: https://www.rustfinity.com/learn/rust/structs/defining-and-using-structs Shows how to access individual fields of a 'User' struct instance using dot notation. This allows retrieval of specific data points like ID, username, or email. ```rust fn main() { let user = User { id: 1, username: String::from("john_doe"), email: String::from("jon@doe.com"), }; println!("User ID: {}", user.id); println!("Username: {}", user.username); println!("Email: {}", user.email); } ``` -------------------------------- ### Rust Function Returning Sum (Shorthand Syntax) Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Illustrates the shorthand syntax in Rust for returning a value from a function. The `return` keyword and the semicolon are omitted from the last expression, allowing Rust to automatically return its value. ```rust fn add(a: i32, b: i32) -> i32 { a + b } ``` -------------------------------- ### Rust: Cloning a String for Independent Use Source: https://www.rustfinity.com/learn/rust/ownership/ownership-rules Illustrates how to use the `clone()` method to create a deep copy of a String, allowing both the original and the new variable to be used independently without ownership conflicts. ```rust fn main(){ let x = String::from("Hello"); let y = x.clone(); // Value has been re-allocated (cloned) println!("x is {}", x); println!("y is {}", y); } ``` -------------------------------- ### Rust Multi-line Comments Source: https://www.rustfinity.com/learn/rust/the-programming-basics/comments Illustrates multi-line comments in Rust, enclosed by `/*` and `*/`. These comments can span multiple lines and are also ignored by the compiler. ```rust fn main() { /* This is a multi-line comment It can span multiple lines */ let x = 5; } ``` -------------------------------- ### Rust: Moving Ownership of a String Source: https://www.rustfinity.com/learn/rust/ownership/ownership-rules Demonstrates how ownership of a String is moved when assigned to a new variable, resulting in the original variable becoming invalid and causing a compile error if accessed. ```rust fn main(){ let x = String::from("Hello"); let y = x; // `x` is moved to `y` // println!("x is {}", x); // Compile error: value borrowed here after move println!("y is {}", y); } ``` -------------------------------- ### Call Associated Function `new` and Print Dragon Instance in Rust Source: https://www.rustfinity.com/learn/rust/structs/implementing-methods This Rust code demonstrates how to call the associated function `new` on the `Dragon` struct to create a new instance named 'Smaug'. It then prints the created `Dragon` instance to the console using the debug formatter `{:?}`. This showcases the usage of associated functions without needing an existing instance. ```rust fn main() { let new_dragon = Dragon::new("Smaug"); println!("{:?}", new_dragon); } ``` -------------------------------- ### Add 'rand' Crate Dependency Source: https://www.rustfinity.com/learn/rust/number-guessing-game This command adds the 'rand' crate, a popular external library for generating random numbers, to the project's dependencies. Cargo will download and manage this dependency, updating the 'Cargo.toml' file automatically. ```bash cargo add rand ``` -------------------------------- ### Rust: Implement `level_up` with return value for Dragon Source: https://www.rustfinity.com/learn/rust/structs/implementing-methods Implements the `level_up` method for the `Dragon` struct, modified to return a tuple `(u32, u32)` containing the new level and fire power. This demonstrates returning values from methods. ```rust impl Dragon { fn level_up(&mut self) -> (u32, u32) { self.level += 1; self.fire_power += 10; println!("{} leveled up to level {}!", self.name, self.level); (self.level, self.fire_power) } fn make_sound(&self) { println!("{} roars!", self.name); } fn attack(&self) { println!("{} attacks with a fireball!", self.name); } } ``` -------------------------------- ### Implement Rust Book Struct 'is_available()' Method Source: https://www.rustfinity.com/learn/rust/structs/challenge Implements the 'is_available()' method for the 'Book' struct. This method returns a boolean value indicating the current availability status of the book without modifying it. ```rust impl Book { fn is_available(&self) -> bool { self.available } } ``` -------------------------------- ### Rust Array Declaration and Initialization Source: https://www.rustfinity.com/learn/rust/the-programming-basics/data-types Demonstrates the declaration and basic usage of arrays in Rust. Arrays are fixed-size collections of elements of the same type, declared using square brackets. ```rust fn main() { let a = [1, 2, 3, 4, 5]; println!("The value of a is: {:?}", a); } ``` -------------------------------- ### Rust: Returning Ownership from a Function Source: https://www.rustfinity.com/learn/rust/ownership/ownership-rules Shows how a function can return ownership of a `String` by specifying it in the return type (`-> String`). This allows the calling function to reclaim ownership and reuse the variable. ```rust fn main(){ let s = String::from("Hello"); let s = takes_ownership(s); println!("s is {}", s); } fn takes_ownership(s: String) -> String { // Gives back the ownership println!("s is {}", s); s } ``` -------------------------------- ### Rust Function Returning Sum of Two Integers Source: https://www.rustfinity.com/learn/rust/the-programming-basics/functions Demonstrates a Rust function that accepts two `i32` integers and returns their sum as an `i32`. It explicitly defines the return type using `-> i32` and uses the `return` keyword. ```rust fn add(a: i32, b: i32) -> i32 { // Added `-> i32` to specify the return type return a + b; } ``` -------------------------------- ### Implement Rust Book Struct 'borrow()' Method Source: https://www.rustfinity.com/learn/rust/structs/challenge Implements the 'borrow()' method for the 'Book' struct. This method mutates the 'available' field to 'false', indicating that the book has been borrowed. ```rust impl Book { fn borrow(&mut self) { self.available = false; } } ``` -------------------------------- ### Define and Use Rust Tuple Structs Source: https://www.rustfinity.com/learn/rust/structs/struct-types Shows how to define and use tuple structs, which group data by type without explicit field names. Access fields using dot notation and their index. ```rust struct Color(i32, i32, i32); let c = Color(255, 0, 0); println!("The color is RGB ({}, {}, {})", c.0, c.1, c.2); ``` -------------------------------- ### Accessing Rust Tuple Elements Using Dot Notation Source: https://www.rustfinity.com/learn/rust/the-programming-basics/data-types Demonstrates accessing individual elements of a Rust tuple by their zero-based index using dot notation. This method is straightforward for accessing specific tuple elements. ```rust fn main() { let tup = (999, 3.14, 1); println!("The value of x is: {}", tup.0); println!("The value of y is: {}", tup.1); println!("The value of z is: {}", tup.2); } ``` -------------------------------- ### Mutable Borrowing in Rust Source: https://www.rustfinity.com/learn/rust/ownership/borrowing Demonstrates how to use a mutable reference (&mut String) to modify a String. This requires the original variable to be declared as mutable and the reference to be passed mutably. ```rust fn change_str(s: &mut String) { s.push_str(", some other text..."); } fn main() { let mut s = String::from("Hello"); change_str(&mut s); println!("From main: {}", s); } ``` -------------------------------- ### Rust Array Slice: Various Sub-array Views Source: https://www.rustfinity.com/learn/rust/ownership/strings-and-slices This Rust code illustrates different ways to create slices from an array, showcasing flexibility in defining the range. It includes creating a slice of the entire array, a slice from the beginning up to a specific index, and a slice from a specific index to the end. ```rust let numbers = [1, 2, 3, 4, 5]; let complete_slice = &numbers[..]; // Slice of the entire array let from_start_slice = &numbers[..3]; // Slice from start to index 3 (exclusive) let to_end_slice = &numbers[2..]; // Slice from index 2 to the end ``` -------------------------------- ### Rust If Else If Chain Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/if-expressions Demonstrates how to chain multiple conditions using `else if` and `else` in Rust. This allows for checking a series of conditions sequentially and executing the block corresponding to the first true condition. ```rust fn main() { let grades = 90; if grades >= 90 { println!("You got an A"); } else if grades >= 80 { println!("You got a B"); } else if grades >= 70 { println!("You got a C"); } else { println!("You got an F"); } } ``` -------------------------------- ### Define a Struct in Rust Source: https://www.rustfinity.com/learn/rust/structs This code defines a basic struct named 'User' with fields for id, username, and email. Structs in Rust are custom data types that group related values of different types. ```rust struct User { id: i32, username: String, email: String, } ``` -------------------------------- ### Debug Rust Structs with `derive(Debug)` Source: https://www.rustfinity.com/learn/rust/structs/defining-and-using-structs This Rust code demonstrates how to enable debugging output for a struct by deriving the `Debug` trait. It defines a `Dog` struct and then prints an instance of it to the console using the `{:?}` format specifier. The `#[derive(Debug)]` attribute automatically implements the necessary trait, resolving potential compilation errors. ```rust #[derive(Debug)] struct Dog { name: String, breed: String, } fn main() { let dog = Dog { name: String::from("Buddy"), breed: String::from("Golden Retriever"), }; println!("{:?}", dog); } ``` -------------------------------- ### Rust Floating-Point Number Declaration and Usage Source: https://www.rustfinity.com/learn/rust/the-programming-basics/data-types Demonstrates how to declare and use floating-point numbers in Rust, showcasing type inference for f64 and explicit declaration for f32. Floating-point numbers have fractional components. ```rust fn main() { let x = 2.0; // Type is inferred as f64 let y: f32 = 3.0; // Rust will use the type f32 for y println!("The value of x is: {}", x); println!("The value of y is: {}", y); } ``` -------------------------------- ### Immutable Borrowing in Rust Source: https://www.rustfinity.com/learn/rust/ownership/borrowing Shows how to pass an immutable reference (&String) to a function, allowing it to read the data without taking ownership. The original owner can still use the data after the function call. ```rust fn print_str(s: &String) { println!("s is {}", s); } fn main(){ let s = String::from("Hello"); print_str(&s); println!("s is {}", s); // Still can use the value, because we have ownership of it } ``` -------------------------------- ### Define and Use Rust Structs with Named Fields Source: https://www.rustfinity.com/learn/rust/structs/struct-types Demonstrates defining a struct with named fields and accessing them using dot notation. This is the most common way to define structs when fields have meaningful names. ```rust struct Point { name: String, x: i32, y: i32, } let p = Point { name: String::from("origin"), x: 0, y: 0 }; println!("The point is at ({}, {})", p.x, p.y); ``` -------------------------------- ### Rust If Expression with Else Source: https://www.rustfinity.com/learn/rust/the-programming-basics/control-flow/if-expressions Demonstrates the basic usage of if and else blocks in Rust to execute code conditionally based on a boolean expression. This is fundamental for controlling program flow. ```rust fn main() { let number = 3; if number < 5 { println!("The number is less than 5"); } else { println!("The number is greater than or equal to 5"); } } ``` ```rust fn main() { let number = 10; if number < 5 { println!("The number is less than 5"); } else { println!("The number is greater than or equal to 5"); } } ``` -------------------------------- ### Rust: Data Race - Simultaneous Mutable and Immutable References Source: https://www.rustfinity.com/learn/rust/ownership/borrowing This Rust code demonstrates a data race scenario where mutable and immutable references to the same String are used concurrently. The Rust compiler prevents this at compile time to ensure data integrity and prevent unexpected changes. ```rust fn main() { let mut s = String::from("hello"); let r1 = &s; let r2 = &s; let r3 = &mut s; println!("r1: {}, r2: {}, r3: {}", r1, r2, r3); } ``` -------------------------------- ### Rust Struct Definitions Summary Source: https://www.rustfinity.com/learn/rust/structs/struct-types A concise summary of the three struct types defined in Rust: named-field, tuple, and unit structs. This highlights their fundamental differences in field definition. ```rust // Struct with named fields struct Point { name: String, x: i32, y: i32, } // Tuple struct struct Color(i32, i32, i32); // Unit struct struct Empty; ``` -------------------------------- ### Accessing Rust Array Elements by Index Source: https://www.rustfinity.com/learn/rust/the-programming-basics/data-types Demonstrates how to access individual elements of a Rust array using zero-based indexing. It highlights that Rust will panic at runtime if an out-of-bounds index is accessed, preventing undefined behavior common in other languages. ```rust fn main() { let a = [1, 2, 3, 4, 5]; println!("The first element of a is: {}", a[0]); println!("The second element of a is: {}", a[1]); println!("The third element of a is: {}", a[2]); println!("The fourth element of a is: {}", a[3]); println!("The fifth element of a is: {}", a[4]); } ``` -------------------------------- ### Rust: Compile-Time Safety - Immutable References First, Then Mutable Source: https://www.rustfinity.com/learn/rust/ownership/borrowing This Rust code demonstrates that mutable borrows are allowed after immutable references have been used, provided the immutable references are not used afterwards. This is safe because the compiler can guarantee the data hasn't changed unexpectedly before the mutable borrow. ```rust fn main() { let mut s = String::from("hello"); let r1 = &s; let r2 = &s; println!("r1: {}, r2: {}", r1, r2); // Mutable borrow later is fine because the // immutable references are not used after this point let r3 = &mut s; println!("r3: {}", r3); } ``` -------------------------------- ### Rust Integer Overflow Behavior (Debug vs. Release) Source: https://www.rustfinity.com/learn/rust/the-programming-basics/data-types Demonstrates the difference in integer overflow handling between Rust's debug and release build modes. In debug mode, overflow causes a panic, while in release mode, it results in wraparound arithmetic. ```rust fn main() { // Example of potential overflow if not careful let x: u8 = 255; // let y = x.checked_add(1).expect("Overflow occurred!"); // This would panic in debug // In release, x + 1 would wrap around to 0 for u8 println!("Max u8 value: {}", x); } ```