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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | struct MyListIter{ data: Vec<i32>, position: i32 } impl Iterator for MyListIter { type Item=i32; fn next(&mut self) -> Option<Self::Item>{ self.position+=1; return if self.position > self.data.len() as i32 { None } else { Some(self.position) } } } fn main() { let data=vec![1, 3, 4]; let mut data_iter = MyListIter{data:data, position:0}; let my_vec: Vec<i32> = data_iter.collect(); println!("{:?}", my_vec); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | use std::collections::VecDeque; use std::iter::FromIterator; fn main() { let mut values = VecDeque::from_iter(&[1, 2, 3]); values.push_back(&4); values.push_front(&0); println!("{:?}", values); let mut values_b = VecDeque::from_iter(vec![1, 2, 3]); values_b.push_back(5); values_b.push_front(-1); println!("{:?}", values_b); } |
When we run the codes, we get the following output.
1 2 | [0, 1, 2, 3, 4] [-1, 1, 2, 3, 5] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 | use std::collections::LinkedList; fn main() { let mut my_list:LinkedList<String> = LinkedList::new(); my_list.push_back(String::from("Elephant")); my_list.push_back(String::from("Lion")); my_list.push_back(String::from("Alligator")); println!("{:?}", my_list); } |
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.