szaydel
7/23/2018 - 4:29 AM

Simple Queue Implementation in Golang

package main

import (
	"fmt"
)

// Queue is a struct which contains a channel
// and length value with which channel is initialized.
type Queue struct {
	buf    chan int
	length int
}

// NewQueue returns pointer to ready-to-go queue with
// specified length.
func NewQueue(items uint16) *Queue {
	return &Queue{
		length: int(items),
		buf:    make(chan int, items),
	}
}

// Len returns length of queue.
func (q *Queue) Len() int {
	return len(q.buf)
}

// Push puts an item into the queue, if necessary dropping
// an item from the queue to make space.
func (q *Queue) Push(v int) {
	if len(q.buf) < q.length {
		q.buf <- v
		return
	}
	<-q.buf // purge item from buffer
	q.buf <- v

}

// Pop pops an item off of the queue.
func (q *Queue) Pop() int {
	return <-q.buf
}

func main() {

	a := NewQueue(100)
	a.Push(1)
	a.Push(10)
	a.Push(100)
	a.Push(1000)
	a.Push(10000)
	a.Push(100000)
	a.Push(1000000)
	a.Push(10000000)
	a.Push(100000000)
	a.Push(1000000000)
	for a.Len() > 0 {
		fmt.Printf("len: %d %d\n", a.Len(), a.Pop())
	}

}