Rust Arrays & Vectors Tutorial | Fixed vs Dynamic Collections for Beginners
Video: Rust Arrays & Vectors Tutorial | Fixed vs Dynamic Collections for Beginners by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Arrays & Vectors Tutorial | Fixed vs Dynamic Collections for Beginners
Rust offers two primary collection types for storing multiple values: arrays and vectors. Arrays have a fixed size known at compile time, while vectors are dynamic and can grow or shrink during runtime. This tutorial demonstrates how to create, access, and iterate over both arrays and vectors, providing a solid foundation for managing collections in Rust.
Code
fn main() {
// Arrays: fixed-size collection of integers
let numbers = [10, 20, 30, 40, 50];
println!("First element: {}", numbers[0]); // Access first element (index 0)
println!("Array length: {}", numbers.len()); // Get array length
// Vectors: dynamic-size collection of strings
let mut fruits = Vec::new(); // Create a new empty vector
fruits.push("Apple"); // Add elements
fruits.push("Banana");
fruits.push("Cherry");
println!("Fruits: {:?}", fruits); // Print entire vector
// Iterating over an array
let scores = [85, 92, 78, 95, 88];
let mut total = 0;
for score in scores {
println!("Score: {}", score); // Print each score
total += score; // Sum scores
}
let average = total as f64 / scores.len() as f64; // Calculate average
println!("Total: {}", total);
println!("Average: {:.2}", average);
}
Key Points
- Arrays have a fixed size determined at compile time and store elements of the same type.
- Vectors are dynamic collections that can grow or shrink using methods like
push(). - Both arrays and vectors are zero-indexed, meaning indexing starts at 0.
- Use
len()to get the number of elements in arrays and vectors. - For loops provide a simple way to iterate over elements in both arrays and vectors.