如何在Golang中获取切片的最后一个元素?

时间:2014-03-20 14:19:37

标签: go slice

提取Go的最后一个元素的slice方式是什么?

var slice []int

slice = append(slice, 2)
slice = append(slice, 7)

slice[len(slice)-1:][0] // Retrieves the last element

上面的解决方案有效,但似乎很尴尬。

3 个答案:

答案 0 :(得分:243)

仅读取切片的最后一个元素:

sl[len(sl)-1]

删除它:

sl = sl[:len(sl)-1]

请参阅此page about slice tricks

答案 1 :(得分:0)

更尴尬的是你的程序在空切片上崩溃!

要处理空切片——零长度导致 panic: runtime error,您可以使用 if/then/else 序列,或者您可以使用临时切片来解决问题。

package main

import (
    "fmt"
)

func main() {
    // test when slice is not empty
    itemsTest1 := []string{"apple", "grape", "orange", "peach", "mango"}

    tmpitems := append([]string{"none"},itemsTest1...)
    lastitem := tmpitems[len(tmpitems)-1]
    fmt.Printf("lastitem: %v\n", lastitem)

    // test when slice is empty
    itemsTest2 := []string{}

    tmpitems = append([]string{"none"},itemsTest2...) // <--- put a "default" first
    lastitem = tmpitems[len(tmpitems)-1]
    fmt.Printf("lastitem: %v\n", lastitem)
}

这会给你这个输出:

lastitem: mango
lastitem: none

对于 []int 切片,您可能需要 -10 作为默认值。

从更高层次思考,如果你的切片总是带有一个默认值,那么“tmp”切片可以被消除。

答案 2 :(得分:-6)

不那么优雅,但也可以这样做:

sl[len(sl)-1: len(sl)]
相关问题