Added a package test.
This commit is contained in:
parent
f38eeefd09
commit
9598e15616
14
hello.go
14
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
|
||||
}
|
||||
|
|
17
helloStack.go
Normal file
17
helloStack.go
Normal 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
27
lib/stack.go
Normal 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.
|
||||
// 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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user