To insert an item at a specific index in a vector in Rust, you can use the insert()
method of the Vec
type. This method allows you to insert an element at the specified index in the vector.
In this example,
vec!
macro.insert()
method to insert the integer at the desired index.fn main() {
// Create a mutable vector of integers
let mut numbers = vec![1, 2, 3, 4, 5];
// Declare an integer to insert
let new_number = 10;
// Index to insert
let index = 2;
// Insert the integer at the desired index
numbers.insert(index, new_number);
// Print the updated vector
println!("{:?}", numbers);
}
[1, 10, 2, 3, 4, 5]
In this example,
vec!
macro.insert()
method to insert the string at the desired index.fn main() {
// Create a mutable vector of strings
let mut words = vec!["apple", "banana", "orange"];
// Declare a string to insert
let new_word = "grape";
// Index to insert
let index = 1;
// Insert the string at the desired index
words.insert(index, new_word);
// Print the updated vector
println!("{:?}", words);
}
["apple", "grape", "banana", "orange"]
In this tutorial, we learned How to Insert an Item at Specific Index in a Vector in Rust language with well detailed examples.