Created
October 9, 2017 12:57
-
-
Save kylehodgetts/63355af19f3479f6e147de4f6d72160d to your computer and use it in GitHub Desktop.
Queue Imp in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Collection []interface{} | |
type IQueue interface { | |
insert(e interface{}) | |
pop() interface{} | |
peek() interface{} | |
} | |
type IntQueue struct { | |
queue Collection | |
} | |
func (queue *IntQueue) insert(e interface{}) { | |
queue.queue = append(queue.queue, e) | |
} | |
func (queue *IntQueue) peek() (i interface{}, err error) { | |
if len(queue.queue) > 0 { | |
i := queue.queue[0] | |
return i, nil | |
} | |
return nil, fmt.Errorf("Queue empty") | |
} | |
func (queue *IntQueue) pop() (i interface{}, err error) { | |
ret, err := queue.peek() | |
if err != nil { | |
return nil, err | |
} | |
queue.queue = queue.queue[1:] | |
return ret, nil | |
} | |
func printOutput(elem interface{}, err error) { | |
if err == nil { | |
fmt.Println(elem) | |
} else { | |
fmt.Println(err) | |
} | |
} | |
func main() { | |
queue := &IntQueue{} | |
printOutput(queue.peek()) | |
printOutput(queue.pop()) | |
queue.insert(1) | |
queue.insert(2) | |
queue.insert(3) | |
fmt.Println(queue.queue) | |
printOutput(queue.peek()) | |
printOutput(queue.pop()) | |
fmt.Println(queue.queue) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment