go - 在 golang 中寻找合理的堆栈实现?

标签 go

到目前为止,我的幼稚方法是

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/

相关文章:

go - 在 golang webapp 中处理 post 请求时显示进度

mongodb - 无法从 `[]string` 断言类型 `[]interface{}`

loops - 使用 goroutine 无限期地迭代文件

opencv - 如何将 Cloud Vision API 导出模型与 Open CV 程序结合使用?

json - 将 docker ps 输出格式化为 JSON 的 Golang 模板

Go:将字节读入数组

memory-management - 在 GO 中处理大内存块

datetime - 将格式化时间转换为 UTC 毫秒

go - 遍历 *goquery.Selection

inheritance - Golang 方法覆盖