How do I (succinctly) remove the first element from a slice in Go?

前端 未结 2 1974
轻奢々
轻奢々 2021-02-02 06:11

I\'ve built a simple queue in Go. It uses an internal slice to keep track of its elements. Elements are pushed onto the queue by appending to the slice. I\'d like to implement <

2条回答
  •  借酒劲吻你
    2021-02-02 06:45

    If you want a ring buffer or FIFO structure then using a slice as in @Everton's answer will cause garbage collection problems as the underlying array may grow indefinitely.

    The easiest way to do this in go, provided you don't mind having a limited size, is to use a channel which is also safe for concurrent access. This is such a common idiom in go that you wouldn't usually bother wrapping it in a type like the below.

    Eg (Playground)

    package main
    
    import "fmt"
    
    type Queue struct {
        elements chan interface{}
    }
    
    func NewQueue(size int) *Queue {
        return &Queue{
            elements: make(chan interface{}, size),
        }
    }
    
    func (queue *Queue) Push(element interface{}) {
        select {
        case queue.elements <- element:
        default:
            panic("Queue full")
        }
    }
    
    func (queue *Queue) Pop() interface{} {
        select {
        case e := <-queue.elements:
            return e
        default:
            panic("Queue empty")
        }
        return nil
    }
    
    func main() {
        q := NewQueue(128)
    
        q.Push(1)
        q.Push(2)
        q.Push(3)
        fmt.Printf("Pop %d\n", q.Pop())
        fmt.Printf("Pop %d\n", q.Pop())
        fmt.Printf("Pop %d\n", q.Pop())
        fmt.Printf("Pop %d\n", q.Pop())
    
    }
    

提交回复
热议问题