From 9598e15616531e5ad00fff2ffe7157d6ea83435d Mon Sep 17 00:00:00 2001 From: milo Date: Sat, 20 Feb 2016 00:24:14 +0100 Subject: [PATCH] Added a package test. --- hello.go | 14 ++++++++++++-- helloStack.go | 17 +++++++++++++++++ lib/stack.go | 27 +++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 helloStack.go create mode 100644 lib/stack.go diff --git a/hello.go b/hello.go index ff3c9b5..d36616d 100644 --- a/hello.go +++ b/hello.go @@ -1,7 +1,17 @@ package main -import "fmt" +import( + "../src/lib/" + "fmt" +) 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 } diff --git a/helloStack.go b/helloStack.go new file mode 100644 index 0000000..bfef3fd --- /dev/null +++ b/helloStack.go @@ -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 +} diff --git a/lib/stack.go b/lib/stack.go new file mode 100644 index 0000000..0c37828 --- /dev/null +++ b/lib/stack.go @@ -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. +// It’s 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) +}