rust vector insert

To insert an element into a Rust vector, you can make use of the insert method provided by the Vec type. This method allows you to specify the index at which you want to insert the element. Here is the syntax:

fn insert(&mut self, index: usize, element: T)
  • &mut self refers to the mutable reference to the vector you want to insert the element into.
  • index is the position at which you want to insert the element.
  • element is the value you want to insert into the vector.

Here's an example that demonstrates how to use the insert method:

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

    vec.insert(2, 100);

    println!("{:?}", vec); // Output: [1, 2, 100, 3, 4, 5]
}

In this example, we start with a vector [1, 2, 3, 4, 5]. We then use the insert method to insert the value 100 at index 2. After the insertion, the vector becomes [1, 2, 100, 3, 4, 5].

Please note that when you insert an element into a vector, all subsequent elements will be shifted to the right. The index you provide should be within the range of the vector, otherwise, it will panic at runtime.