如何(简洁地)从Go中的切片中删除第一个元素? [英] How do I (succinctly) remove the first element from a slice in Go?
问题描述
我在Go中建立了一个简单的队列.它使用内部切片来跟踪其元素.通过附加到切片将元素推入队列.我想通过删除 elements
中的第一个元素来实现 .Pop()
.
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 .Pop()
by removing the first element in elements
.
在许多其他语言中,弹出"列表的第一个元素是单行代码,这使我相信下面的实现是草率而冗长的.有更好的方法吗?
In many other languages, "popping" the first element of a list is a one-liner, which leads me to believe my implementation below is sloppy and verbose. Is there a better way?
type Queue struct {
elements []interface{}
}
func (queue *Queue) Push(element interface{}) {
queue.elements = append(queue.elements, element)
}
func (queue *Queue) Pop() interface{} {
element := queue.elements[0]
if len(queue.elements) > 1 {
queue.elements = queue.elements[1:]
} else {
queue.elements = make([]interface{}, 0)
}
return element
}
请注意,如果 len(queue.elements)== 0
,我希望 Queue
惊慌.我不检查界限不是疏忽.
Please note that I wish for the Queue
to panic if len(queue.elements) == 0
. It's not an oversight that I don't check the bounds.
推荐答案
您尝试过这些吗?
从队列弹出
x, a = a[0], a[1:]
从堆栈弹出
x, a = a[len(a)-1], a[:len(a)-1]
推
a = append(a, x)
来自: https://code.google.com/p/go-wiki/wiki/SliceTricks
这篇关于如何(简洁地)从Go中的切片中删除第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!