Skip to content

Instantly share code, notes, and snippets.

@sharonjl
Last active August 10, 2022 01:45
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 sharonjl/878983f510bee0b17ef3829fc17ed9e6 to your computer and use it in GitHub Desktop.
Save sharonjl/878983f510bee0b17ef3829fc17ed9e6 to your computer and use it in GitHub Desktop.
basic queue in go (untested)
package queue
import "sync"
type Queue[T any] struct {
items []T
mu sync.RWMutex
}
func New[T any]() *Queue[T] {
return &Queue[T]{
items: make([]T, 0),
mu: sync.RWMutex{},
}
}
func (q *Queue[T]) Enqueue(item T) {
q.mu.Lock()
defer q.mu.Unlock()
q.items = append(q.items, item)
}
func (q *Queue[T]) Dequeue() T {
q.mu.Lock()
defer q.mu.Unlock()
item := q.items[0]
q.items = q.items[1:]
return item
}
func (q *Queue[T]) Peek() T {
q.mu.RLock()
defer q.mu.RUnlock()
return q.items[0]
}
func (q *Queue[T]) Size() int {
q.mu.RLock()
defer q.mu.RUnlock()
return len(q.items)
}
func (q *Queue[T]) Clear() {
q.mu.Lock()
defer q.mu.Unlock()
q.items = make([]T, 0)
}
func (q *Queue[T]) Iterator() <-chan T {
ch := make(chan T)
go func() {
q.mu.RLock()
c := q.items[:]
q.mu.RUnlock()
for _, i := range c {
ch <- i
}
close(ch)
}()
return ch
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment