Creating a vector in Rust

To create Vector simply follow the below-listed methods.

1. Using Vec::new() Method:

let v : Vec<i64> = Vec::new();  

Here v is the initialized vector that will contain the 64-bit integer datatype. It is initialized with help of the Vec::new() method.

Rust




fn main() {
 
    let v : Vec<i64> = Vec::new(); 
 
    // printing the size of vector
    println!("{ }",v.len());
}


Output: 

2. Using macro in Rust: 

let v = vec!['G','E','E','K','S'];   

Here this vector created using the macro vec!.  And it stores the value that we provide here which is char type.

Rust




fn main() {
 
    let v = vec!['G','E','E','K','S'];
 
    // printing the size of vector
    println!("{ }",v.len());
}


Output: 

Rust – Vectors

Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take  O(1) complexity. Vectors ensure they never allocate more than isize::MAX bytes.

A simple way of explaining a vector is that it is a container that stores the values like an array, but it has more advantages than an array data structure. It can be increase size dynamically during runtime. It provided by the standard library that can be store the value of any data type. The data of the vector is allocated on the heap. Its length defines the number of elements present in the vector. Its capacity defines the actual allocated space on the heap of this vector that is in the form of 2^n.

Syntax:

Vec<T> 

Where T denotes type of data.

Similar Reads

Creating a vector in Rust:

To create Vector simply follow the below-listed methods....

Accessing a Vector:

...

Updating a Vector:

...