Rust, Software Development

Rust – How to Create a List Using Vec, VecDeque, and LinkedList

In Rust, we may refer to any list as a sequence of items. A list can be fixed size like an array or resizeable collection types – Vec, VecDeque, and LinkedList. Meaning the list can grow or shrink at runtime. This post shows how to create lists of items in Rust using Vec, VecDeque, and LinkedList.

Create a List Using Vec

Let’s start with creating a list using Vec. We can derive a Vec instance from Iterators or using the vec! macro. Consider the following codes wherein we derive an Iterator from an array.

Line 20 creates a Vec using the vec! macro. Normally, we use Vec when – 1) we don’t care about the sort order of list elements, and 2) we want a resizable list in Rust. Most of the time, Vec is a go-to type for creating general lists.

Create a List Using VecDeque

Next, we create a list in Rust using the VecDeque type. VecDeque is similar to Vec but has additional functions for queue operations to conform with the FIFO(First-In-First-Out) principle. Consider the following codes that create a VecDeque instance from an Iterator and Vec instance.

When we run the codes, we get the following output.

We sometimes want a list that represents a queue with operations to insert elements at both ends of the list.

Create LinkedList

Lastly, we have LinkedList. We can use LinkedList to create lists in Rust, quite similar to using Vec and VecDeque. To create a list in Rust using LinkedList, consider the following codes. With LinkedList, we generally use the new function to create an instance. Then, add elements for later processing.

Although LinkedList is much more flexible, it is generally inefficient. Note that both Vec and VecDeque are array-based containers. Therefore, they are generally faster, more memory efficient, and make better use of CPU cache.

We tested the codes using Rust 1.53.0.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like