To initialize a vector in Rust, you can use the vec!
macro, which creates a new vector containing the specified elements.
In this example,
vec!
macro to create a vector containing integers. The vec!
macro takes a list of values separated by commas and creates a vector with those values.vec!
macro, we provide integer values.int_vector
.println!
macro to display its contents.fn main() {
let int_vector = vec![1, 2, 3, 4, 5];
println!("{:?}", int_vector);
}
[1, 2, 3, 4, 5]
In this example,
vec!
macro to create a vector containing strings. The vec!
macro takes a list of values separated by commas and creates a vector with those values.vec!
macro, we provide string values enclosed in double quotes.str_vector
.println!
macro to display its contents.fn main() {
let str_vector = vec!["apple", "banana", "cherry"];
println!("{:?}", str_vector);
}
["apple", "banana", "cherry"]
In this example,
vec!
macro to create a vector containing boolean values. The vec!
macro takes a list of values separated by commas and creates a vector with those values.vec!
macro, we provide boolean values (true
or false
).bool_vector
.println!
macro to display its contents.fn main() {
let bool_vector = vec![true, false, true];
println!("{:?}", bool_vector);
}
[true, false, true]
In this tutorial, we learned How to Initialize a Vector in Rust language with well detailed examples.