Skip to content

Instantly share code, notes, and snippets.

@aalvarado
Created February 23, 2019 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalvarado/f25867ca7a501763c2025f5fddf54ed2 to your computer and use it in GitHub Desktop.
Save aalvarado/f25867ca7a501763c2025f5fddf54ed2 to your computer and use it in GitHub Desktop.
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