Golang doesn’t have default implementations of queue and stack but it’s pretty simple to implement.
Queue FIFO
Let say we want to have integers queue, we can easily accomplish it by using golang slices, below is example:
for simplisity I did’t add queue size functionality
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
type integersQueue []int func (q *integersQueue) put(v int) { *q = append(*q, v) } func (q *integersQueue) get() (int, error){ if len(*q)==0 { return 0, errors.New("queue is empty") } r := (*q)[0] *q = (*q)[1:] return r,nil } func (q *integersQueue) isEmpty() bool { if len(*q)==0 { return true } return false } |
Stack LIFO
Implementig stack is very similar to queue, here again we are gonna use slices
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
type integersStack []int func(s *integersStack) push(v int){ *s = append(*s, v) } func(s *integersStack) pop() (int, error) { if len(*s) == 0 { return 0, errors.New("stack is empty") } ret := (*s)[len(*s)-1] *s = (*s)[0:len(*s)-1] return ret,nil } |