Rust Iterators
Overview
Iterators are powerful tools for processing data collections in Rust.
🔄 Basic Iterators
rust
fn main() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
for val in v1_iter {
println!("Got: {}", val);
}
}🔧 Iterator Adapters
rust
fn main() {
let v1: Vec<i32> = vec![1, 2, 3];
let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();
println!("{:?}", v2);
}Continue learning: Next chapter - Rust Closures
Rust Closures
Overview
Closures are anonymous functions that can capture their surrounding environment.
🔧 Basic Closures
rust
fn main() {
let expensive_closure = |num| {
println!("calculating slowly...");
std::thread::sleep(std::time::Duration::from_secs(2));
num
};
println!("{}", expensive_closure(5));
}📦 Capturing Environment
rust
fn main() {
let x = 4;
let equal_to_x = |z| z == x;
let y = 4;
assert!(equal_to_x(y));
}Continue learning: Next chapter - Rust References and Borrowing
Rust References and Borrowing
Overview
References allow you to use values without taking ownership.
🔗 Immutable References
rust
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}🔗 Mutable References
rust
fn main() {
let mut s = String::from("hello");
change(&mut s);
println!("{}", s);
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}Continue learning: Next chapter - Rust Lifetimes
Rust Lifetimes
Overview
Lifetimes ensure the validity of references.
🕐 Lifetime Syntax
rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}Continue learning: Next chapter - Rust Slice Types
Rust Slice Types
Overview
Slices allow you to reference a contiguous sequence of elements in a collection.
🍰 String Slices
rust
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{} {}", hello, world);
}🍰 Array Slices
rust
fn main() {
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
println!("{:?}", slice);
}Continue learning: Next chapter - Rust Structs
Rust Structs
Overview
Structs are custom data types that let you package related values together.
🏗️ Defining Structs
rust
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn main() {
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
println!("User: {}", user1.username);
}🔧 Methods
rust
impl User {
fn new(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
fn is_active(&self) -> bool {
self.active
}
}Continue learning: Next chapter - Rust Enums