//! Comprehensive examples of array methods in Rust
pub fn demonstrate_array_methods() {
println!("\n=== BASIC ARRAY OPERATIONS ===");
// 1. Creation and Initialization
let arr = [1, 2, 3, 4, 5]; // Type: [i32; 5]
let zeros = [0; 5]; // [0, 0, 0, 0, 0]
println!("Created array: {:?}", arr);
println!("Zeros array: {:?}", zeros);
// 2. Accessing Elements
println!("\n=== ACCESSING ELEMENTS ===");
println!("First element: {}", arr[0]); // 1
println!("Last element: {}", arr[arr.len() - 1]); // 5
// Safe access with get()
match arr.get(2) {
Some(val) => println!("Element at index 2: {}", val),
None => println!("Index out of bounds"),
}
// 3. Iteration Methods
println!("\n=== ITERATION METHODS ===");
println!("Iterating with for:");
for element in &arr {
print!("{} ", element);
}
println!();
println!("Iterating with enumerate():");
for (index, value) in arr.iter().enumerate() {
println!(" {}: {}", index, value);
}
// 4. Searching Methods
println!("\n=== SEARCHING METHODS ===");
println!("Contains 3? {}", arr.contains(&3)); // true
println!("Position of 4: {:?}", arr.iter().position(|&x| x == 4)); // Some(3)
println!("Find first even: {:?}", arr.iter().find(|&&x| x % 2 == 0)); // Some(2)
// 5. Transformation Methods
println!("\n=== TRANSFORMATION METHODS ===");
let squared: Vec<i32> = arr.iter().map(|x| x * x).collect();
println!("Squared: {:?}", squared);
let evens: Vec<i32> = arr.iter().filter(|&x| x % 2 == 0).copied().collect();
println!("Even numbers: {:?}", evens);
// 6. Sorting and Manipulation (requires mutable)
println!("\n=== SORTING AND MANIPULATION ===");
let mut mut_arr = [5, 3, 1, 4, 2];
mut_arr.sort();
println!("Sorted: {:?}", mut_arr);
mut_arr.reverse();
println!("Reversed: {:?}", mut_arr);
mut_arr.fill(42);
println!("Filled with 42: {:?}", mut_arr);
// 7. Conversion Methods
println!("\n=== CONVERSION METHODS ===");
let vec = arr.to_vec(); // Convert to Vec
println!("As Vec: {:?}", vec);
let slice = &arr[1..4]; // Get slice
println!("Slice [1..4]: {:?}", slice);
// 8. Advanced Methods (Rust 1.55+)
println!("\n=== ADVANCED METHODS ===");
let arrays = [[1, 2], [3, 4], [5, 6]];
println!("Flattened: {:?}", arrays.flatten());
let chunked = arr.array_chunks::<2>();
println!("Array chunks:");
for chunk in chunked {
println!(" {:?}", chunk);
}
}
// Remember to add to src/menu_items/mod.rs:
// pub mod array_methods;