Rust Interview Questions

35 Questions
Rust

Rust

Web DevelopmentIoT

Question 10

How do you create a vector in Rust?

Answer:

In Rust, a vector is a dynamic array that can grow or shrink in size. It is one of the most commonly used collection types in Rust, provided by the standard library. You can create a vector in several ways. Here are the main methods to create and initialize a vector in Rust:

1. Using Vec::new()

This creates an empty vector that you can push elements onto later.

fn main() {
    let mut v: Vec<i32> = Vec::new();
    v.push(1);
    v.push(2);
    v.push(3);
    println!("{:?}", v); // Output: [1, 2, 3]
}

2. Using the vec! Macro

This macro allows you to create a vector with initial elements easily.

fn main() {
    let v = vec![1, 2, 3];
    println!("{:?}", v); // Output: [1, 2, 3]
}

3. Creating a Vector with a Specific Size and Default Values

You can create a vector of a specific size where all elements are initialized to the same value using the vec! macro or Vec::with_capacity.

fn main() {
    let v = vec![0; 5]; // Creates a vector of five elements, all initialized to 0
    println!("{:?}", v); // Output: [0, 0, 0, 0, 0]
}

4. Using Vec::with_capacity

This method creates a vector with a specified capacity. It is useful when you know how many elements you will store in advance and want to avoid multiple reallocations.

fn main() {
    let mut v = Vec::with_capacity(10); // Creates a vector with capacity for 10 elements
    for i in 0..10 {
        v.push(i);
    }
    println!("{:?}", v); // Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}

5. Using Iterators to Create a Vector

You can create a vector from an iterator, which is useful for generating values dynamically.

fn main() {
    let v: Vec<i32> = (0..5).collect();
    println!("{:?}", v); // Output: [0, 1, 2, 3, 4]
}

Example Usage

Combining these methods in practical usage:

fn main() {
    // Creating a vector using Vec::new()
    let mut v1: Vec<i32> = Vec::new();
    v1.push(1);
    v1.push(2);

    // Creating a vector using the vec! macro
    let v2 = vec![3, 4, 5];

    // Creating a vector with a specific size and default value
    let v3 = vec![0; 3];

    // Creating a vector with Vec::with_capacity
    let mut v4 = Vec::with_capacity(2);
    v4.push(6);
    v4.push(7);

    // Creating a vector from an iterator
    let v5: Vec<i32> = (8..11).collect();

    println!("v1: {:?}", v1);
    println!("v2: {:?}", v2);
    println!("v3: {:?}", v3);
    println!("v4: {:?}", v4);
    println!("v5: {:?}", v5);
}

Output:

v1: [1, 2]
v2: [3, 4, 5]
v3: [0, 0, 0]
v4: [6, 7]
v5: [8, 9, 10]

These methods provide flexibility in how you can create and initialize vectors in Rust, depending on your needs.

Recent job openings