To append an item to a vector in Rust, you can use the push()
method provided by the Vec type. This method allows you to add elements to the end of the vector dynamically.
In this example,
vec
with some initial elements.push
method to append a new item to the vector.// Create a vector with initial elements
let mut vec = vec![1, 2, 3];
// Append item to the vector using push method
vec.push(4);
// Print the modified vector
println!("{:?}", vec);
[1, 2, 3, 4]
In this example,
strings
with some initial strings.push
method to append a new string to the vector.// Create a vector of strings with initial strings
let mut strings = vec!["hello", "world"];
// Append a string to the vector using push method
strings.push("rust");
// Print the modified vector
println!("{:?}", strings);
["hello", "world", "rust"]
In this tutorial, we learned How to Append an Item to a Vector in Rust language with well detailed examples.