Vectors in Rust Programming


Vectors in Rust are like re-sizable arrays. They are used to store objects that are of the same type and they are stored contiguously in memory

Like Slices, their size is not known at compile-time and can grow or shrink accordingly. It is denoted by Vec<T> in Rust

The data stored in the vector is allocated on the heap.

Example

In the below example, a vector named d is created using the Vec::new(); function that Rust provides.

fn main() {
   let mut d: Vec = Vec::new();
   d.push(10);
   d.push(11);
   println!("{:?}", d);
   d.pop();
   println!("{:?}", d);
}

We push the elements into a vector using the push() function and we remove the elements using the pop() function.

Output

[10, 11]
[10]

Rust also provides us with another way to create a vector. Instead of using the Vec::new() function, we can make use of vec! Macro.

Example

Live Demo

fn main() {
   let v = vec![1,2,3];
   println!("{:?}",v);
}

Output

[1, 2, 3]

The above vector is not mutable and if we try to mutate some of its values, then we will get an error.

Example

Live Demo

fn main() {
   let v = vec![1,2,3];
   println!("{:?}",v);
   v[0] = 99;
   println!("{:?}",v);
}

Output

  |
4 | let v = vec![1,2,3];
  | - help: consider changing this to be mutable: `mut v`
5 | println!("{:?}",v);
6 | v[0] = 99;
  | ^ cannot borrow as mutable

We can make it mutable by adding the mut keyword in front of the name of the vector we are defining.

Example

Live Demo

fn main() {
   let mut v = vec![1,2,3];
   println!("{:?}",v);
   v[0] = 99;
   println!("{:?}",v);
}

Output

[1, 2, 3]
[99, 2, 3]

Lastly, it should be remembered that whenever the length of the vector exceeds the capacity, then the capacity of the vector will be increased automatically.

Updated on: 05-Apr-2021

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements