In Rust, arrays and slices are two commonly used data structures that can store a sequence of elements. However, they have some differences in usage and functionality. I'll first introduce how to define them, and then demonstrate their usage with examples.
Array
Arrays in Rust are fixed-size collections stored on the stack, with all elements of the same type.
Defining Arrays
The definition format is let array_name: [Type; size] = [element0, element1, ..., elementN];. Here's an example:
rustlet numbers: [i32; 5] = [1, 2, 3, 4, 5];
Here, we define an array named numbers consisting of five i32 integers.
Using Arrays
To access elements in an array, you can use indexing, starting from 0. For example, retrieving the first element of the above array:
rustlet first = numbers[0];
Slice
A slice is a reference to an array, borrowing a portion of data without owning it. The size of a slice can vary at runtime.
Defining Slices
Slices are typically borrowed from arrays, with the definition format &array[start..end], where start is the inclusive starting index and end is the exclusive ending index. For example:
rustlet slice = &numbers[1..4];
Here, slice is a slice containing elements 2 to 4 (exclusive of index 4) from the numbers array.
Using Slices
Slices can access elements via indexing like arrays, but cannot modify element values unless using a mutable reference. For example, accessing the first element of the slice:
rustlet first_in_slice = slice[0];
Example: Using Arrays and Slices
Suppose we need to calculate the sum of all elements in a slice of an array. Here's how to implement it:
rustfn sum_slice(slice: &[i32]) -> i32 { let mut sum = 0; for &item in slice.iter() { sum += item; } sum } fn main() { let numbers: [i32; 5] = [10, 20, 30, 40, 50]; let slice = &numbers[1..4]; let result = sum_slice(slice); println!("Sum of slice: {}", result); // Output: Sum of slice: 90 }
In this example, we define a function sum_slice to calculate the sum of elements in a slice. In the main function, we create an array and a slice, then call sum_slice to compute the sum.
This demonstrates how arrays and slices are defined and used in Rust, as well as their application in practical programming tasks.