go自定义堆栈Stack
学习GO中自定义类型的定义,接口和方法的写法
测试用例: https://github.com/panyingyun/gostudy/blob/master/testStack.go
package main
import (
"fmt"
"github.com/panyingyun/gostudy/stacker"
)
func main() {
a := stacker.NewStack(2)
a.Push("Google")
a.Push(100)
a.Push([]int{1, 2, 3})
fmt.Println(a)
fmt.Println(a.Len())
fmt.Println(a.Cap())
for {
item, err := a.Pop()
if err != nil {
fmt.Println(err)
break
}
fmt.Println(item)
}
}
stack定义:
https://github.com/panyingyun/gostudy/blob/master/stacker/stack.go
package stacker
import (
"errors"
)
type Stack struct {
st []interface{}
len int
cap int
}
func NewStack(cap int) *Stack {
st := make([]interface{}, 0, cap)
return &Stack{st, 0, cap}
}
func (s *Stack) Len() int {
return s.len
}
func (s *Stack) Cap() int {
return s.cap
}
func (s *Stack) Push(p interface{}) {
s.st = append(s.st, p)
s.len = len(s.st)
s.cap = cap(s.st)
}
func (s *Stack) Pop() (interface{}, error) {
if s.len == 0 {
return nil, errors.New("Can't pop an empty stack")
}
s.len -= 1
out := s.st[s.len]
s.st = s.st[:s.len]
return out, nil
}