Arrays and linked lists are both ways to store multiple items. Why does accessing an element by its position in an array usually take less time than in a linked list?
Think about how memory is arranged for arrays versus linked lists.
Arrays store elements one after another in memory. This lets the computer calculate exactly where an element is by its position, so it can jump directly to it. Linked lists store elements scattered in memory, connected by pointers, so you must follow links one by one to reach an element.
Consider this Rust code that inserts values into an array. What will be printed?
fn main() {
let mut arr = [0; 5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
println!("{:?}", arr);
}Look at how the array is initialized and which positions are assigned values.
The array starts with five zeros. We assign 10 to index 0, 20 to index 1, and 30 to index 2. The rest remain zero.
Look at this Rust code snippet. Why does it panic at runtime?
fn main() {
let arr = [1, 2, 3];
println!("{}", arr[3]);
}Remember that Rust arrays start at index 0 and the last valid index is length minus one.
The array has elements at indexes 0, 1, and 2. Accessing index 3 is out of bounds and causes a panic.
What will this Rust program print?
fn main() {
let arr = [2, 4, 6, 8];
let mut sum = 0;
for i in 0..arr.len() {
sum += arr[i];
}
println!("{}", sum);
}Add all the numbers in the array: 2 + 4 + 6 + 8.
The sum of 2, 4, 6, and 8 is 20, so the program prints 20.
Rust arrays have a fixed size known at compile time. Why is this design important and what problem does it solve?
Think about how fixed size helps the compiler and memory management.
Knowing the size at compile time lets Rust allocate arrays on the stack, which is faster and safer than heap allocation. This avoids runtime overhead and potential memory errors.
