A Queue is a linear structure which follows the First-In-First-Out (FIFO) principle. This means that the elements added first are the ones that get removed first.
For implementation details on the Queue Library please see the Sway Libs Docs .
In order to use the Queue Library, the Queue Library must be added to your Forc.toml file and then imported into your Sway project.
To add the Queue Library as a dependency to your Forc.toml file in your project, use the forc add command.
forc add [email protected]NOTE: Be sure to set the version to the latest release.
To import the Queue Library to your Sway Smart Contract, add the following to your Sway file:
use queue::*; Once the Queue has been imported, you can create a new queue instance by calling the new function.
let mut queue = Queue::new(); Adding elements to the Queue can be done using the enqueue function.
// Enqueue an element to the queue
queue.enqueue(10u8); To remove elements from the Queue, the dequeue function is used. This function follows the FIFO principle.
// Dequeue the first element and unwrap the value
let first_item = queue.dequeue().unwrap(); To retrieve the element at the head of the Queue without removing it, you can use the peek function.
// Peek at the head of the queue
let head_item = queue.peek(); The is_empty and len functions can be used to check if the queue is empty and to get the number of elements in the queue respectively.
// Checks if queue is empty (returns True or False)
let is_queue_empty = queue.is_empty();
// Returns length of queue
let queue_length = queue.len();