WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 11 of 100

What are arrays and vectors in Rust? Explain their differences.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics