Skip to content

Instantly share code, notes, and snippets.

@aalvarado aalvarado/main.rs
Created Feb 23, 2019

Embed
What would you like to do?
Naive circular queue in Rust
use std::fmt;
#[derive(Debug)]
struct CircularQueue<T> {
max: usize,
list: Vec<T>,
}
impl <T> CircularQueue<T> where T: std::string::ToString {
pub fn new(max: usize) -> CircularQueue<T> {
CircularQueue {
max: max,
list: Vec::new(),
}
}
pub fn enq(&mut self, number: T) {
self.list.push(number)
}
// Not really a `shift` here. The way remove works, is
// by removing the element and then shifting everything left.
pub fn deq(&mut self) -> T {
self.list.remove(0)
}
}
impl <T> fmt::Display for CircularQueue<T> where T: std::string::ToString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]",
self.list.iter().fold(String::new(), |acc, num| acc + &num.to_string() + ", ")
)
}
}
fn main() {
let mut cq = CircularQueue::new(7);
cq.enq(1);
cq.enq(2);
println!("{}", cq);
cq.deq();
println!("{}", cq);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.