Day 12a: Introduction to Arrays in Rust – Basics, Syntax, and Simple Operations

Venkat Annangi
Venkat Annangi
01/10/2024 03:57 4 min read 66 views
#rust-arrays #rust #108 days of rust

Day 12a: Introduction to Arrays in Rust – Basics, Syntax, and Simple Operations

Welcome to Day 11 of our journey through Rust! Today, we're diving into arrays, a fundamental data structure in any programming language. Arrays in Rust are quite unique compared to some other languages due to their fixed size and the strong type system Rust enforces. Let’s explore how arrays work, how to use them effectively, and why they’re an essential tool in your Rust toolkit.

1. What is an Array in Rust?

An array in Rust is a collection of elements of the same type, stored in contiguous memory. Arrays have a fixed size, meaning their length is determined at compile time and cannot be changed during runtime. This makes arrays efficient but less flexible compared to other collections like vectors.

Arrays are useful when you need to store a known, fixed number of items, such as days of the week or a collection of scores in a game.

Example of an Array:

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

In this example, we create an array called numbers with five integer elements. The length of the array is fixed at five, and each element can be accessed by its index.

2. Declaring Arrays in Rust

Arrays are declared using square brackets [], and the type annotation includes both the element type and the array length.

Syntax:

let array_name: [type; length] = [value1, value2, value3, ...];

Example:

fn main() {
    let temperatures: [f64; 4] = [32.5, 28.0, 30.1, 29.4];
    println!("Temperature on day 2: {}", temperatures[1]);
}

In this example, the array temperatures is defined with four f64 elements. The type annotation [f64; 4] specifies that the array contains four floating-point numbers.

a. Default Initialization

You can initialize an array with the same value for all elements by specifying the value and using the ; length syntax.

Example:

fn main() {
    let zeros = [0; 5]; // Creates an array of 5 elements, all initialized to 0
    println!("Array of zeros: {:?}", zeros);
}

The array zeros has five elements, all set to 0. This can be useful for creating arrays with default values.

3. Accessing Array Elements

Array elements are accessed using indices, which start at 0. To access an element, use the syntax array[index].

Example:

fn main() {
    let fruits = ["apple", "banana", "cherry"];
    
    let first_fruit = fruits[0];
    println!("First fruit: {}", first_fruit);
}

In this example, fruits[0] returns the first element of the array, which is "apple".

4. Common Operations with Arrays

Arrays allow you to perform several common operations, such as getting the length, iterating over elements, and copying arrays.

a. Getting the Length of an Array

You can get the length of an array using the len() method.

Example:

fn main() {
    let numbers = [10, 20, 30, 40, 50];
    println!("The length of the array is: {}", numbers.len());
}

The len() method returns the number of elements in the array, which in this case is 5.

b. Iterating Over Arrays

You can use a for loop to iterate over the elements of an array.

Example:

fn main() {
    let numbers = [1, 2, 3, 4, 5];

    for number in numbers {
        println!("Number: {}", number);
    }
}

In this example, the for loop iterates over each element in the array, printing it to the console.

c. Array Copying

In Rust, arrays implement the Copy trait, meaning they can be copied simply by assignment. This is different from other collections like vectors, which require explicit cloning.

Example:

fn main() {
    let original = [1, 2, 3];
    let copy = original;

    println!("Original: {:?}", original);
    println!("Copy: {:?}", copy);
}

Both original and copy contain the same elements, and changing one will not affect the other.

Conclusion

Arrays are a fundamental part of Rust's data structures, allowing you to store multiple values of the same type in a fixed-size collection. They are simple, efficient, and perfect when you need to work with a known number of elements. Today, we've covered the basics of declaring arrays, accessing their elements, and performing some common operations.

In the next post, Day 12b, we'll explore slicing, borrowing, and more common use cases for arrays. Stay tuned as we dive deeper into the versatility of arrays in Rust!

Comments