As an exercise for learning Go I am writing a basic Queue data structure. I started learning about interfaces yesterday I thought it would be cool to try and use them for this exercise. What I am trying to accomplish is to have a Queue
that can accept any type that implements this interface:
type Queuable interface {
Next() *Queuable // This is probably not right
}
Basically what I want is to be able to add any type that has a Next()
method to my Queue
. So what I tried was:
type Node struct {
value interface{}
next *Queuable
}
// Next gets the next object
func (n *Node) Next() *Queuable {
return n.next
}
// Job - A job for the queue
type Job struct {
instruction string
next *Queuable
}
// Next gets the next object
func (j *Job) Next() *Queuable {
return j.next
}
// Queue ...
type Queue struct {
head *Queuable
size int
}
And my methods looking like:
func (q *Queue) Enqueue(node *Queuable) {
...
}
// Dequeue - Remove a Queueable form the Queue
func (q *Queue) Dequeue() *Queuable {
result := q.head
q.head = q.head.Next()
q.size--
return result
}
I'm getting a ton of these errors (basically on any line with an assignment):
current.Next undefined (type *Queuable is pointer to interface, not interface)
So ultimately what I would like to do would be:
func main() {
queue := NewQueue() // Helper function not pictured
job := &Job{"some instructions", nil}
node := &Node{5, nil}
queue.Enqueue(node) // queue = [node]
queue.Enqueue(job) // queue = [node, job]
queue.Dequeue() // node
queue.Dequeue() // job
}