Logo

Programming-Idioms

  • C
  • Ruby
  • Rust

Idiom #325 Create a queue

Create a new queue q, then enqueue two elements x and y, then dequeue an element into the variable z.

use std::collections::VecDeque;
let mut q = VecDeque::new();
q.push_back(x);
q.push_back(x);
let z = q.pop_front(); 
println!("1st item ~> {}",z.unwrap());
q = Queue.new
q.enq(x)
q.enq(y)
z = q.deq
type Queue[T any] struct {
	items []T
}

func (q *Queue[T]) Enqueue(t T) {
	q.items = append(q.items, t)
}

func (q *Queue[T]) Dequeue() T {
	t := q.items[0]
	var zero T
	q.items[0] = zero
	q.items = q.items[1:]
	return t
}

q := new(Queue[string])
q.Enqueue(x)
q.Enqueue(y)
z := q.Dequeue()

The generic type Queue works for any type parameter T

New implementation...
< >
programming-idioms.org