登录
首页 >  Golang >  Go问答

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

来源:Golang技术栈

时间:2023-03-21 16:19:34 369浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《How do I (succinctly) remove the first element from a slice in Go?》,正文内容主要涉及到golang等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

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
}

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.

正确答案

Did you try these?

Pop from queue

x, a = a[0], a[1:]

Pop from stack

x, a = a[len(a)-1], a[:len(a)-1]

Push

a = append(a, x)

From: https://code.google.com/p/go-wiki/wiki/SliceTricks

今天关于《How do I (succinctly) remove the first element from a slice in Go?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>