Vector

A vector is nothing but a type of an array whose size can be changed at the run time. Vector instances are created to declare a vector and then is initialized.

In Rust, there are standard library collections which can be used to implements different data structures efficiently. Vectors are one of those collections.

Property of Rust Vector :
  • A vector is declared as an instance.
  • A vector size can grow or shrink dynamically, that is in the run time.
  • A vector stores the data exactly like a typical array store with a unique index
  • A vector appends values on in the rear end, therefore using the concept of a stack.
  • A vector's memory is allocated in the heap.
Creating a vector instance:

An instance of a vector can be created in different ways. The two most used ways are:

  • Syntax using the Vec structure and a static method new()! :
let instance_name = Ved :: new()!
  • Syntax using the macro vec!
let vector_name = vec![data_1,data_2,...data_n]

Now in the program example below, we shall use any two methods of vector initialization:

A program to print a list of integers :

fn main() {
   let mut my_vector = Vec::new();
   my_vector.push(1);
   my_vector.push(2);
   my_vector.push(3);
   my_vector.push(4);
   my_vector.push(5);
   println!("The values inside the vector is {:?}",my_vector);
}

In the above program, we have created an instance of a vector called- my_vector by let mut my_vector = Vec::new();. And then we have used the function push() , and used the dot (.) operator along with the instance name to push the integer value inside the vector.

Program Output :

rust-vector-example

Now the same program can be created, by initializing the vector using the new! macro.

Program to print a list of integers :

fn main() {
   let my_vector = vec![1,2,3,4,5];
   println!("The contents of the vector are: {:?}", my_vector);
}

In the above program, a vector instance- my_vector, is directly initialized using the macro new!. This is done in this way- let my_vector = vec![1,2,3,4,5]; . Then using the macro println!(), simply instance is printed.

Program Out :

rust-vector-example-another

Functions for implementing vectors

There are several functions which are required to carry out several operations for implementing vectors. These functions are stored in the Rust library and can be called to create an instance, push an element into the vector, etc.

Below is the list of some of the most useful and important functions:

  • new() : This function create and new and empty vector. No memory will be allocated by this vector until and unless any element is inserted into the vector.
  • push() : This function will append an element at the back of a collection(E.g: vector)
  • remove() : This function retrieves and removes the element in the mentioned index and then shift all the elements to the left.
  • contains() : This function returns a true if a specific value is matched or found.
  • len() : This function returns the number of elements in the vector, which is also the length of the vector.
Program using new() and push()

The method new() is used to create an instance of a vector and the push() method appends an element into the vector.

Program to push five elements in a vector and display them.

fn main() {
   let mut my_vector = Vec::new();
   my_vector.push(1);
   my_vector.push(2);
   my_vector.push(3);
   my_vector.push(4);
   my_vector.push(5);
   println!("The values inside the vector is {:?}",my_vector);
}

In the above program, we have created an instance of a vector called- my_vector by let mut my_vector = Vec::new();. And then we have used the function push() , and used the dot (.) operator along with the instance name to push the integer value inside the vector.

Program Output :

rust-vector-example

Program using remove()

This function will remove the element in a particular index and then shift all the elements after it to the left.

Syntax for remove()

vector_name.remove(index); 

Program to remove the element at position 1 (index 1) :

fn main() {
   let mut my_vector = vec![10,20,30,40,50];
   my_vector.remove(1); 
   println!("{:?}",my_vector);
}

In the above program, we have initialized a vector instance and assigned it with values- 10, 20, 30, 40 and 50. And then, we append the function remove(), with a dot (.) operator.

Program Output :

rust-vector-element-remove

Program using contains()

The function contains(), returns a true, if the slice contains an element with a specific value. This method can be used to search an element in the vector as well as find the index of an element.

To assure whether the contains() function returns a true, we can use it with a decisional statement like if, so that if it returns a true, a certain code gets executed, otherwise, if it returns false, then another code may get executed.

Syntax for contains() :

 if vector_name.contains( & value) {
  // some code
 }
 else {
  //some code
 }

Program to check whether a value is present in the vector :

fn main() {
   let my_vector = vec![1,2,3,4,5,6,7,8,9];
   if my_vector.contains(& 5) {
      println!(" 5 is pressent in the vector");
   }
   println!("{:?}",my_vector);
}

Program Output :

rust-vector-element-search

Program using len()

The function len(), returns the number of elements in the vector, which is also the length of the vector. This can be done by simply appending the len() with the dot (.) operator.

Syntax for len()

vector_name.len()

Program to find the length a vector (number of elements in a vector)

fn main() {
   let my_vector = vec![1,2,3];
   println!("size of vector is :{}",my_vector.len());
}

Program Outptut :

rust-vector-length

We can also, assign the return value of the function len(), to a value and print it.

fn main() {
   let my_vector = vec![1,2,3,4,5];
   let length= my_vector.len();
   println!("The length of the vector is of vector is :{}", length);
}

Output :

rust-vector-length-value

Value retrieval for Vector

Accessing value from a vector is simple. Just as array elements are accessed using the index, the vector elements are also retrieved using the index.

Syntax :

vector_name[index]

Below is a program where we shall push some elements into the vector using the push() macro and try to retrieve the data using the vector index.

Program to store and retrieve data :

fn main() {
   let mut my_vector = Vec::new();
   my_vector.push(100);
   my_vector.push(200);
   my_vector.push(300);
   my_vector.push(400);
   my_vector.push(500);
   println!("The element in the index 0 is {:?}",my_vector[0]);
   println!("The element in the index 3 is {:?}",my_vector[3]);
}

In the above program, we have pushed five elements into the vector, and then tried to print the element at index 0 and index 3, which are 100, and 400 respectively.

rust-vector-display

Array Vs Vector

  • The size of an array cannot be changed at the run time, it's fixed. On the other hand, the size of the vector is not fixed and can be changed dynamically, that is in the run time.
  • A vector can store objects as well as values. On the other hand, an array can only store values and not objects.
  • Memory handling is possible in vectors since the size can be dynamically allocated. On the other hand, memory handling is not possible in case of an array, since the size cannot be changed dynamically.
  • An array is a scalar data structure. On the other hand, a vector is a vector-type data structure.
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions