To create a vector of size N in Rust, you can use the vec!
macro with the [value; N]
syntax to initialize a vector with N elements all set to a specified value.
In this example,
vec!
macro to create a vector of integers. The vec!
macro takes a list of values or uses the [value; N]
syntax to initialize a vector with N elements.[0; n]
to create a vector of size n
with all elements set to 0.int_vector
.println!
macro to display its contents.fn main() {
let n = 5;
let int_vector = vec![0; n];
println!("{:?}", int_vector);
}
[0, 0, 0, 0, 0]
In this example,
vec!
macro to create a vector of strings. The vec!
macro takes a list of values or uses the [value; N]
syntax to initialize a vector with N elements.[String::from(""); n]
to create a vector of size n
with all elements set to an empty string.str_vector
.println!
macro to display its contents.fn main() {
let n = 5;
let str_vector = vec![String::from(""); n];
println!("{:?}", str_vector);
}
["", "", "", "", ""]
In this example,
vec!
macro to create a vector of booleans. The vec!
macro takes a list of values or uses the [value; N]
syntax to initialize a vector with N elements.[false; n]
to create a vector of size n
with all elements set to false
.bool_vector
.println!
macro to display its contents.fn main() {
let n = 5;
let bool_vector = vec![false; n];
println!("{:?}", bool_vector);
}
[false, false, false, false, false]
In this tutorial, we learned How to create a Vector of Size N in Rust language with well detailed examples.