Arrays and Slices in Rust

 

What are Arrays? 

An array in Rust is a fixed-size collection of elements of the same type. If you like things orderly and predictable, arrays are your best friends!

Declaring an Array

fn main() {
    let numbers: [i32; 5] = [1, 2, 3, 4, 5];
    println!("First element: {}", numbers[0]);
}

 Fixed size: Once declared, the size cannot be changed!  Zero-based indexing: First element is at index 0. Efficient: Stored in stack memory, so it's super fast!

Creating an Array with Default Values

fn main() {
    let zeros = [0; 10]; // Creates an array with 10 elements, all set to 0.
    println!("Last element: {}", zeros[9]);
}

[value; size] syntax initializes an array with repeating values.

What are Slices? 

A slice is a dynamically-sized reference to a portion of an array. It’s like saying, "Give me a piece of that array, please!"

Creating a Slice

fn main() {
    let numbers = [10, 20, 30, 40, 50];
    let slice = &numbers[1..4]; // Slice from index 1 to 3 (4 is exclusive)
    println!("Slice: {:?}", slice);
}

 Borrowed from an array (no ownership transfer). Dynamic size: Unlike arrays, slices don’t have a fixed length.  Immutable by default, but mutable slices exist too!

Mutable Slice Example

fn main() {
    let mut values = [1, 2, 3, 4, 5];
    let slice = &mut values[2..4];
    slice[0] = 99; // Modifying slice also modifies the original array!
    println!("Updated array: {:?}", values);
}

Slices are references, so changes reflect in the original array.

Why Use Arrays and Slices?

Arrays are great when you need fixed-size collections.  Slices provide flexibility and efficiency when working with parts of an array.  Both are memory-efficient, making Rust super safe and fast!

Post a Comment

0 Comments