到目前为止,我的幼稚方法是
type stack []int
func (s *stack) Push(v int) {
*s = append(*s, v)
}
func (s *stack) Pop() int {
res:=(*s)[len(*s)-1]
*s=(*s)[:len(*s)-1]
return res
}
它有效 - playground ,但看起来很丑,并且有太多的取消引用。我能做得更好吗?
最佳答案
这是风格和个人品味的问题,你的代码很好(除了不是线程安全的并且如果你从一个空堆栈中弹出会 panic )。为了稍微简化它,您可以使用值方法并返回堆栈本身,它稍微更优雅对某些人来说。即
type stack []int
func (s stack) Push(v int) stack {
return append(s, v)
}
func (s stack) Pop() (stack, int) {
// FIXME: What do we do if the stack is empty, though?
l := len(s)
return s[:l-1], s[l-1]
}
func main(){
s := make(stack,0)
s = s.Push(1)
s = s.Push(2)
s = s.Push(3)
s, p := s.Pop()
fmt.Println(p)
}
另一种方法是将其包装在结构中,因此您还可以轻松添加互斥锁以避免竞争条件等:
type stack struct {
lock sync.Mutex // you don't have to do this if you don't want thread safety
s []int
}
func NewStack() *stack {
return &stack {sync.Mutex{}, make([]int,0), }
}
func (s *stack) Push(v int) {
s.lock.Lock()
defer s.lock.Unlock()
s.s = append(s.s, v)
}
func (s *stack) Pop() (int, error) {
s.lock.Lock()
defer s.lock.Unlock()
l := len(s.s)
if l == 0 {
return 0, errors.New("Empty Stack")
}
res := s.s[l-1]
s.s = s.s[:l-1]
return res, nil
}
func main(){
s := NewStack()
s.Push(1)
s.Push(2)
s.Push(3)
fmt.Println(s.Pop())
fmt.Println(s.Pop())
fmt.Println(s.Pop())
}
关于go - 在 golang 中寻找合理的堆栈实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28541609/