go.fifo provides a simple FIFO thread-safe queue. *fifo.Queue supports pushing an item at the end with Add(), and popping an item from the front with Next(). There is no intermediate type for the stored data. Data is directly added and retrieved as type interface{} The queue itself is implemented as a single-linked list of chunks containing max 64 items each.
go get github.com/foize/go.fifo
package main
import (
"github.com/foize/go.fifo""fmt"
)
funcmain() {
// create a new queuenumbers:=fifo.NewQueue()
// add items to the queuenumbers.Add(42)
numbers.Add(123)
numbers.Add(456)
// retrieve items from the queuefmt.Println(numbers.Next()) // 42fmt.Println(numbers.Next()) // 123fmt.Println(numbers.Next()) // 456
}package main
import (
"github.com/foize/go.fifo""fmt"
)
typethingstruct {
TextstringNumberint
}
funcmain() {
// create a new queuethings:=fifo.NewQueue()
// add items to the queuethings.Add(&thing{
Text: "one thing",
Number: 1,
})
things.Add(&thing {
Text: "another thing",
Number: 2,
})
// retrieve items from the queuefor {
// get a new item from the things queueitem:=things.Next();
// check if there was an itemifitem==nil {
fmt.Println("queue is empty")
return
}
// assert the type for the itemsomeThing:=item.(*thing)
// print the fieldsfmt.Println(someThing.Text)
fmt.Printf("with number: %d\n", someThing.Number)
}
}
/* output: */// one thing// with number: 1// another thing// with number: 2// queue is emptyDocumentation can be found at godoc.org/github.com/foize/go.fifo. For more detailed documentation, read the source.
This package is based on github.com/yasushi-saito/fifo_queue There are several differences:
- renamed package to
fifoto make usage simpler - removed intermediate type
Itemand now directly using interface{} instead. - renamed (*Queue).PushBack() to (*Queue).Add()
- renamed (*Queue).PopFront() to (*Queue).Next()
- Next() will not panic on empty queue, will just return nil interface{}
- Add() does not accept nil interface{} and will panic when trying to add nil interface{}.
- Made fifo.Queue thread/goroutine-safe (sync.Mutex)
- Added a lot of comments
- renamed internal variable/field names