Rust Lang

How to Use Data Structures in Rust

Rust uses the collections library to support and implement several common data structures. A collection refers to a collection of one or more values stored in the heap memory. This means that the collection size does not need to be known before compilation.

Collections are very useful when implementing flexible and generic data storage. Most collections can shrink or grow in the program.

Let us explore various data structures in the Rust programming language and how to perform the basic operations.

Here, we have the four major categories for the Rust collections:

  1. Sequences
  2. Maps
  3. Sets
  4. Misc

Let us discuss each category in detail.

Sequence Collections

Here, we will discuss the three types of sequence collections in Rust:

  1. Vec
  2. VecDeque
  3. LinkedList

Vec

A vec or vector is a contiguous growable array that stores values in a list, one after another in the memory.

To create a new empty vector, use the new method as shown below:

let mut vec = Vec::new();

Then, you can add elements to the vector using the push method:

vec.push(1);
vec.push(2);

To print a vector, use the debug trait as provided below:

println!("{:?}", vec);

Remove the element in a vector using the remove method and the index of the element to remove, as shown below:

Vec.remove(0); // remove element at index 0
println!("{:?}", vec);

VecDeque

A VecDeque or double-ended vector is a non-contiguous growable ring buffer. We can create a new empty buffer using the new method as provided below:

use std::collections::VecDeque;
let mut deque = VecDeque::new();

The VecDeque uses push_front() and push_back() methods to add elements to the front or back of the Deque:

    Deque.push_front(1);
    deque.push_front(2);
    deque.push_front(3);
    // push back
    deque.push_back(4);
    deque.push_back(5);

To print the elements of the VecDeque, use the debug trait:

Println!("{:?}", deque);

To remove elements from a VecDeque, use the pop_front() and pop_back() methods to remove an element from the front and back of the Deque respectively.

The following example is provided below:

deque.pop_back();
deque.pop_front();
println!("{:?}", deque);

This should return as shown below:

[3, 2, 1, 4, 5]
[2, 1, 4]

LinkedList

This is a doubly linked list with owned nodes. It is useful when you need a vector or Deque of unknown size.

To create a new empty LinkedList, use the following:

use std::collections::LinkedList;
let mut lnk = LinkedList::new();

We use the push_front() and push_back() methods to add elements to the front and back of a linked list, respectively.

For example:

let mut lnk = LinkedList::new();
lnk.push_front(3);
lnk.push_front(2);
lnk.push_front(1);
lnk.push_back(4);
lnk.push_back(5);
println!("{:?}", lnk);

The previous example should return as follows:

[1, 2, 3, 4, 5]

To remove elements from a linked list, use the pop_front and pop_back methods:

lnk.pop_back();
lnk.pop_front();
println!("{:?}", lnk);

The output is as shown:

[1, 2, 3, 4, 5] // before
[2, 3, 4] // after

Map Collections

The second category of Rust collections in Maps, and these include:

  1. HashMap
  2. BTreeMap

HashMap

A HashMap allows you to store mapping of key-value pairs. It uses a hashing function to determine how the keys and values are stored in memory. They are very useful when you need to store related values. It uses a key instead of an index to retrieve values.

To create a new HashMap, use the following syntax:

use std::collections::HashMap;
let mut map = HashMap::new();

To insert key-value pairs to a HashMap, use the following insert method:

map.insert(0, "Angular");
map.insert(1, "React");
map.insert(3, "mithril");
map.insert(4, "Vue");

To print a HashMap, use the following:

println!("{:?}", map);

This should return as shown below:

{1: "React", 2: "Svelte", 3: "mithril", 4: "Vue", 0: "Angular"}

Keep in mind that the key and value can be any supported type.

To delete elements from a HashMap, use the remove()method as follows:

map.remove(1);

BTreeMap

You notice that a HashMap is not sorted. If you are looking for a sorted map, use the BTreeMap. Each element in the BTreeMap is stored in its own heap-allocated node.

To create a new BTreeMap, use the following:

use std::collections::BTreeMap;
let mut btree = BTreeMap::new();

To add elements, use the following insert method.

btree.insert("key", "value");

To delete an element, use the remove method as:

btree.remove("key");

Set Collections

The next category of Rust collections is sets. These types are derived from the set theory, and they include:

  1. HashSets
  2. BTreeSet

HashSets

A HashSet is closely similar to a HashMap. This means it is a set form of a HashMap and does not allow duplicate values.

To create a new hashset, use the following syntax:

use std::collections::HashSet;
let mut set = HashSet::new();

Use the insert and remove methods to add and delete elements from a HashMap, respectively.

set.insert("a");
set.remove("a");

BTreeSet

This is a set implementation of a BTreeMap. We can create a new BTreeSet as shown below:

use std::collections::BTreeSet;
let mut set = BTreeSet::new();

Insert and remove elements as provided below:

set.insert("A");
set.remove("A");

Misc Collections

There is only one type in the Misc collections.

  1. BinaryHeap

BinaryHeap

Binary heap allows you to implement an ample binary tree. You can create a new binary heap as provided below:

use std::collections::BinaryHeap;
let mut heap = BinaryHeap::new();

To add elements, use the following push method:

heap.push("item");

To remove a value, use the following pop method:

heap.pop();

The pop method removes the greatest item in a heap.

Conclusion

This guide covers the popular and useful data structures and their basic operations in the Rust programming language. In addition, we discussed in detail the four major categories of the Rust collections, such as sequences, maps, sets, and misc. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list