Added a package test.

This commit is contained in:
Mikkel Milo 2016-02-20 00:24:14 +01:00
parent f38eeefd09
commit 9598e15616
3 changed files with 56 additions and 2 deletions

View File

@ -1,7 +1,17 @@
package main package main
import "fmt" import(
"../src/lib/"
"fmt"
)
func main() { func main() {
fmt.Printf("Hello, World") var s collection.Stack
s.Push("world")
s.Push("hello, ")
for s.Size() > 0 {
fmt.Print(s.Pop())
}
fmt.Println()
// Output: hello, world
} }

17
helloStack.go Normal file
View File

@ -0,0 +1,17 @@
package collection_test
import (
collection "."
"fmt"
)
func Example() {
var s collection.Stack
s.Push("world")
s.Push("hello, ")
for s.Size() > 0 {
fmt.Print(s.Pop())
}
fmt.Println()
// Output: hello, world
}

27
lib/stack.go Normal file
View File

@ -0,0 +1,27 @@
// Package collection implements a generic stack.
package collection
// The zero value for Stack is an empty stack ready to use.
type Stack struct {
data []interface{}
}
// Push adds x to the top of the stack.
func (s *Stack) Push(x interface{}) {
s.data = append(s.data, x)
}
// Pop removes and returns the top element of the stack.
// Its a run-time error to call Pop on an empty stack.
func (s *Stack) Pop() interface{} {
i := len(s.data) - 1
res := s.data[i]
s.data[i] = nil // to avoid memory leak
s.data = s.data[:i]
return res
}
// Size returns the number of elements in the stack.
func (s *Stack) Size() int {
return len(s.data)
}