Arrays and vectors are two fundamental data structures in Rust which allow us to group same or different types of data elements together.
Arrays are fixed-size data structures that contain elements of the same data type arranged in contiguous memory locations. Once an array is declared, its size cannot be changed. In Rust, arrays are defined using square brackets as shown below:
let names: [String; 3] = ["Alice".to_string(), "Bob".to_string(), "Charlie".to_string()];
In the example above, we define an array called ‘names‘ which contains three elements of type ‘String‘. We specified the length of the array to be ‘3‘ using the type signature.
Arrays in Rust are stack-allocated and accessing their elements uses zero-based indexing. It’s also possible to use array slices to get a subset of the array.
Vectors, on the other hand, are dynamic-size data structures that can grow or shrink as needed. They contain elements of the same data type arranged in contiguous memory locations. Vectors are implemented using a heap-allocated buffer that grows or shrinks as needed. In Rust, vectors are defined using the ‘Vec‘ type as shown below:
let numbers = vec![1, 2, 3];
In the example above, we define a vector called ‘numbers‘ which contains three elements of type ‘i32‘. Notice that we didn’t have to specify the length of the vector as it’s determined at runtime. We used the ‘vec!‘ macro to create and initialize the vector.
Since vectors are dynamically-sized, they can be resized using the ‘push‘ and ‘pop‘ methods. It’s also possible to get vectors slices using the ‘&‘ symbol.
The main difference between arrays and vectors is that arrays have a fixed size while vectors are dynamically-sized. This makes vectors more flexible as they can grow or shrink as needed, while arrays are more performant due to their stack allocation and fixed size.