Queue
A queue is a linear data structure that follows First In First Out (FIFO) principle. Elements are added at the back (enqueue) and removed from the front(deqeue) just like a line in any queue. Queue are used for tasks like scheduling, buffering, asynchronous data handling and so on.
Idiomatic approach to create queue is using VecDeque which is a double-ended queue implementation with a growable ring buffer. The “default” usage of this type as a queue is to use push_back
to add to the queue, and pop_front
to remove from the queue. extend
and append
push onto the back in this manner, and iterating over VecDeque goes front to back.
use std::collections::VecDeque; fn main() { let deque: VecDeque<u32> = VecDeque::with_capacity(10); let _r1 = q.enqueue(1); let _r2 = q.enqueue(2); let _r3 = q.enqueue(3); if let Err(error) = q.enqueue(4) { println!("Enqueue error: {error}"); } if let Some(data) = q.dequeue() { println!("data: {data}"); } else { println!("empty queue"); } println!("size: {}, empty: {}", q.size(), q.is_empty()); println!("content: {:?}", q); }