### Enums and Pattern Matching in Rust Source: https://context7.com/dhghomon/easy_rust/llms.txt Illustrates the creation of enums with and without associated data, and how to use the `match` control flow construct for pattern matching to handle different enum variants. Includes examples of match with ranges and guards. ```rust enum Season { Spring, Summer, Autumn, Winter, } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(u8, u8, u8), } fn describe_season(season: &Season) { match season { Season::Spring => println!("Flowers bloom"), Season::Summer => println!("Time for vacation"), Season::Autumn => println!("Leaves fall"), Season::Winter => println!("Bundle up!"), } } fn process_message(msg: Message) { match msg { Message::Quit => println!("Quitting"), Message::Move { x, y } => println!("Moving to ({}, {})", x, y), Message::Write(text) => println!("Message: {}", text), Message::ChangeColor(r, g, b) => println!("Color: {}, {}, {}", r, g, b), } } fn main() { describe_season(&Season::Summer); let msg = Message::Write(String::from("Hello")); process_message(msg); let number = 15; match number { 1 => println!("One"), 2..=10 => println!("Between 2 and 10"), n if n > 10 => println!("Greater than 10: {}", n), _ => println!("Something else"), } } ``` -------------------------------- ### Handle Nullable Values with Option and Errors with Result in Rust Source: https://context7.com/dhghomon/easy_rust/llms.txt Demonstrates the use of `Option` for handling potentially missing values and `Result` for managing operations that may succeed or fail. Includes examples of `match`, `if let`, `unwrap_or`, and the `?` operator for error propagation. ```rust fn divide(a: f64, b: f64) -> Option { if b == 0.0 { None } else { Some(a / b) } } fn parse_number(s: &str) -> Result { s.parse::() } fn main() { let result = divide(10.0, 2.0); match result { Some(value) => println!("Result: {}", value), None => println!("Cannot divide by zero"), } if let Some(value) = divide(10.0, 5.0) { println!("Got value: {}", value); } let safe_result = divide(10.0, 0.0).unwrap_or(0.0); match parse_number("42") { Ok(n) => println!("Parsed: {}", n), Err(e) => println!("Error: {}", e), } fn parse_and_double(s: &str) -> Result { let number = s.parse::()?; Ok(number * 2) } println!("{:?}", parse_and_double("21")); } ``` -------------------------------- ### Rust HashMap: Key-Value Storage and Operations Source: https://context7.com/dhghomon/easy_rust/llms.txt Demonstrates the usage of `HashMap` in Rust for storing key-value pairs with efficient average O(1) lookup. Covers insertion, retrieval using `get()`, updating values, conditional insertion with `entry().or_insert()`, and iterating over the map. ```rust use std::collections::HashMap; fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Red"), 50); let team = String::from("Blue"); match scores.get(&team) { Some(score) => println!("{}: {}", team, score), None => println!("Team not found"), } scores.insert(String::from("Blue"), 25); scores.entry(String::from("Green")).or_insert(30); scores.entry(String::from("Blue")).or_insert(100); let text = "hello world hello rust hello"; let mut word_count = HashMap::new(); for word in text.split_whitespace() { let count = word_count.entry(word).or_insert(0); *count += 1; } println!("{:?}", word_count); for (key, value) in &scores { println!("{}: {}", key, value); } } ``` -------------------------------- ### Rust Vector Operations Source: https://context7.com/dhghomon/easy_rust/llms.txt Demonstrates the use of `Vec`, Rust's growable array type that stores elements on the heap. It covers creating vectors using `Vec::new()` and the `vec!` macro, performing mutable operations like `push()` and `pop()`, accessing elements by index or using `get()`, iterating over elements, and pre-allocating capacity with `with_capacity()` for performance. ```rust fn main() { // Creating vectors let vec1: Vec = Vec::new(); let vec2 = vec![1, 2, 3, 4, 5]; // vec! macro // Mutable vector operations let mut my_vec = Vec::new(); my_vec.push(10); my_vec.push(20); my_vec.push(30); // Accessing elements println!("First element: {}", my_vec[0]); // 10 println!("Safe access: {:?}", my_vec.get(5)); // None // Iterating for number in &my_vec { println!("{}", number); } // Pre-allocating capacity for performance let mut efficient_vec: Vec = Vec::with_capacity(100); println!("Capacity: {}", efficient_vec.capacity()); // 100 // Popping elements let last = my_vec.pop(); // Some(30) println!("Popped: {:?}", last); } ``` -------------------------------- ### Rust Iterators and Closures: Data Processing Source: https://context7.com/dhghomon/easy_rust/llms.txt Illustrates the use of iterators for lazy sequence processing and closures as anonymous functions in Rust. Examples include mapping, filtering, folding (reducing), and chaining iterator operations, along with `find` and `position` methods. ```rust fn main() { let numbers = vec![1, 2, 3, 4, 5]; let add_one = |x| x + 1; println!("{}", add_one(5)); let doubled: Vec = numbers.iter() .map(|x| x * 2) .collect(); println!("{:?}", doubled); let evens: Vec<&i32> = numbers.iter() .filter(|x| *x % 2 == 0) .collect(); println!("{:?}", evens); let sum: i32 = numbers.iter() .fold(0, |acc, x| acc + x); println!("Sum: {}", sum); let result: i32 = (1..=10) .filter(|x| x % 2 == 0) .map(|x| x * x) .sum(); println!("Sum of squares of evens: {}", result); let found = numbers.iter().find(|&&x| x > 3); println!("First > 3: {:?}", found); let position = numbers.iter().position(|&x| x == 3); println!("Position of 3: {:?}", position); } ``` -------------------------------- ### Rust Modules and Visibility Control Source: https://context7.com/dhghomon/easy_rust/llms.txt Illustrates code organization in Rust using modules and controlling item visibility with the `pub` keyword. It covers nested modules, public functions, structs, and methods. ```rust mod math_utils { // Private by default fn internal_helper(x: i32) -> i32 { x * 2 } // Public function pub fn double(x: i32) -> i32 { internal_helper(x) } // Nested module pub mod advanced { pub fn square(x: i32) -> i32 { x * x } } } // Public struct with mixed visibility mod shapes { pub struct Rectangle { pub width: u32, pub height: u32, id: u32, // private field } impl Rectangle { pub fn new(width: u32, height: u32) -> Self { Self { width, height, id: 0 } } pub fn area(&self) -> u32 { self.width * self.height } } } fn main() { use math_utils::double; use math_utils::advanced::square; use shapes::Rectangle; println!("Double: {}", double(5)); println!("Square: {}", square(4)); let rect = Rectangle::new(10, 20); println!("Area: {}", rect.area()); } ``` -------------------------------- ### Rust Primitive Types and Variables Source: https://context7.com/dhghomon/easy_rust/llms.txt Demonstrates Rust's signed and unsigned integer types, type inference, mutable variables using `mut`, floating-point types, character literals, and type casting with `as`. It also shows how to use underscores for readability in large numbers. ```rust fn main() { // Integer types with explicit type annotation let small_number: u8 = 10; let big_number: i64 = 100_000_000; // underscores for readability // Type inference - Rust chooses i32 for integers by default let my_number = 8; // Mutable variables let mut counter = 0; counter += 1; println!("Counter: {}", counter); // prints: Counter: 1 // Floats: f32 and f64 (default is f64) let my_float: f64 = 5.5; let another_float = 3.14; // inferred as f64 // Characters use single quotes, strings use double quotes let first_letter = 'A'; let cat_face = '😺'; // Type casting with `as` let number: u8 = 100; println!("{}", number as char); // prints: d } ``` -------------------------------- ### Rust Generics: Structs and Functions Source: https://context7.com/dhghomon/easy_rust/llms.txt Demonstrates how to define generic structs (Point, Pair) and implement generic methods in Rust. It also shows a generic function `largest` that works with any type implementing `PartialOrd`. Specific implementations for types like `f64` are also illustrated. ```rust struct Point { x: T, y: T, } struct Pair { first: T, second: U, } impl Point { fn new(x: T, y: T) -> Self { Self { x, y } } fn x(&self) -> &T { &self.x } } impl Point { fn distance_from_origin(&self) -> f64 { (self.x.powi(2) + self.y.powi(2)).sqrt() } } fn largest(list: &[T]) -> &T { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn main() { let int_point = Point::new(5, 10); let float_point = Point::new(1.0, 4.0); println!("x = {}", int_point.x()); println!("Distance: {}", float_point.distance_from_origin()); let numbers = vec![34, 50, 25, 100, 65]; println!("Largest: {}", largest(&numbers)); } ``` -------------------------------- ### Rust Function Declaration and Usage Source: https://context7.com/dhghomon/easy_rust/llms.txt Illustrates how to declare functions in Rust using `fn`, including functions with parameters that require type annotations and functions with specified return types using `->`. It also shows how the last expression without a semicolon is implicitly returned. ```rust // Function with parameters and return type fn multiply(number_one: i32, number_two: i32) -> i32 { let result = number_one * number_two; println!("{} times {} is {}", number_one, number_two, result); result // no semicolon = return this value } // Function returning nothing (unit type) fn print_greeting(name: &str) { println!("Hello, {}!", name); } fn main() { let product = multiply(8, 9); println!("Result: {}", product); // prints: Result: 72 print_greeting("World"); } ``` -------------------------------- ### Define and Use Named, Tuple, and Unit Structs in Rust Source: https://context7.com/dhghomon/easy_rust/llms.txt Demonstrates the definition and usage of different types of structs in Rust: named structs with fields, tuple structs for ordered data, and unit structs for markers. Includes associated functions (constructors) and methods for structs. ```rust struct Country { population: u32, capital: String, leader_name: String, } struct Color(u8, u8, u8); struct FileDirectory; impl Country { fn new(population: u32, capital: String, leader_name: String) -> Self { Self { population, capital, leader_name, } } fn describe(&self) { println!("{} has {} people. Capital: {}", self.leader_name, self.population, self.capital); } } fn main() { let kalmykia = Country::new( 500_000, String::from("Elista"), String::from("Batu Khasikov"), ); kalmykia.describe(); let red = Color(255, 0, 0); println!("Red value: {}", red.0); } ``` -------------------------------- ### Rust Threads and Concurrency: Spawning and Shared State Source: https://context7.com/dhghomon/easy_rust/llms.txt Explains safe concurrent programming in Rust using threads. It shows basic thread spawning with `thread::spawn`, transferring ownership with `move` closures, and managing shared mutable state using `Arc` (Atomic Reference Counting) and `Mutex` (Mutual Exclusion). ```rust use std::thread; use std::sync::{Arc, Mutex}; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..5 { println!("Spawned thread: {}", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..3 { println!("Main thread: {}", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); let data = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Vector: {:?}", data); }); handle.join().unwrap(); let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Counter: {}", *counter.lock().unwrap()); } ``` -------------------------------- ### Implement and Use Traits for Shared Behavior in Rust Source: https://context7.com/dhghomon/easy_rust/llms.txt Explains Rust traits as a way to define shared functionality. Shows how to implement traits for custom types and use trait bounds in generic functions to constrain types based on their implemented behavior. Includes default implementations. ```rust trait Printable { fn format(&self) -> String; fn print(&self) { println!("{}", self.format()); } } struct Article { title: String, author: String, } struct Tweet { username: String, content: String, } impl Printable for Article { fn format(&self) -> String { format!("{} by {}", self.title, self.author) } } impl Printable for Tweet { fn format(&self) -> String { format!("@{}: {}", self.username, self.content) } } fn print_item(item: &T) { item.print(); } fn complex_print(item: &T) { println!("{:?}", item); item.print(); } fn main() { let article = Article { title: String::from("Rust Guide"), author: String::from("Alice"), }; let tweet = Tweet { username: String::from("rustlang"), content: String::from("Rust is awesome!"), }; print_item(&article); print_item(&tweet); } ``` -------------------------------- ### Rust Error Handling with Result and ? Source: https://context7.com/dhghomon/easy_rust/llms.txt Demonstrates idiomatic Rust error handling using the `Result` enum and the `?` operator for concise error propagation. It includes custom error type implementation and handling potential I/O and parsing errors. ```rust use std::fs::File; use std::io::{self, Read}; fn read_file_contents(path: &str) -> Result { let mut file = File::open(path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } // Custom error type #[derive(Debug)] enum AppError { IoError(io::Error), ParseError(std::num::ParseIntError), } impl From for AppError { fn from(err: io::Error) -> Self { AppError::IoError(err) } } impl From for AppError { fn from(err: std::num::ParseIntError) -> Self { AppError::ParseError(err) } } fn process_file(path: &str) -> Result { let contents = std::fs::read_to_string(path)?; let number: i32 = contents.trim().parse()?; Ok(number * 2) } fn main() { match read_file_contents("example.txt") { Ok(contents) => println!("File contents: {}", contents), Err(e) => println!("Error reading file: {}", e), } // Using unwrap_or_else for error handling let contents = read_file_contents("missing.txt") .unwrap_or_else(|_| String::from("Default content")); } ``` -------------------------------- ### Rust String Types and Manipulation Source: https://context7.com/dhghomon/easy_rust/llms.txt Explains Rust's two primary string types: `&str` (string slice, borrowed and immutable) and `String` (owned, heap-allocated, and growable). It demonstrates creating, modifying, converting between types, and using string methods like `len()` and `chars().count()`, as well as the `format!` macro. ```rust fn main() { // &str - string slice (borrowed, immutable) let slice: &str = "Hello, world!"; // String - owned, heap-allocated, growable let mut owned = String::from("Hello"); owned.push_str(", Rust!"); owned.push('!'); // Converting between types let from_slice = slice.to_string(); let also_from_slice = String::from(slice); // String methods println!("Length in bytes: {}", slice.len()); // 13 println!("Length in chars: {}", slice.chars().count()); // 13 // Format macro for string building let name = "Alice"; let age = 30; let formatted = format!("{} is {} years old", name, age); println!("{}", formatted); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.