Thread safe Queue in Rust 🦀
I started my rust journey 1 year ago and I feel like it helped me a lot to become a better developer, even if I primarily work with React and Typescript.
Today I’d like to share with you what I learned about thread safety in rust, by implementing a simple data structure such as a FIFO queue.
Let’s get started by declaring a trait to describe our queues:
trait Queue<T> {
/// Creates a new, empty queue
fn new() -> Self;
/// Enqueue a new value
fn push(&self, value: T);
/// Dequeue a value
/// Returns None if the queue is empty
fn pop(&self) -> Option<T>;
/// Returns the number of elements enqueued
fn len(&self) -> usize;
/// Checks if the `size()` is 0
fn is_empty(&self) -> bool;
}
This trait can then be implemented by a struct or data type to create a queue. The actual implementation of the methods will depend on the type of queue that you want to create.
Implementation
Ok, now that we have our generic trait we can start writing some code for our first queue, the FIFO (*First In, First Out*)
///! queue/mod.rs
use std::collections::VecDeque;
/// A FIFO queue implemented using a VecDeque
struct FifoQueue<T> {
/// The underlying data structure of the queue
data: VecDeque<T>
}