【问题标题】:How to get the last element of a slice?如何获取切片的最后一个元素?
【发布时间】:2014-04-27 11:07:40
【问题描述】:

提取切片最后一个元素的 Go 方法是什么?

var slice []int

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

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

上面的解决方案可行,但看起来很尴尬。

【问题讨论】:

    标签: go slice


    【解决方案1】:

    您可以使用len(arr) 函数,尽管它会返回从 1 开始的切片长度,并且由于 Go 数组/切片从索引 0 开始,最后一个元素实际上是 len(arr)-1

    例子:

    arr := []int{1,2,3,4,5,6} // 6 elements, last element at index 5
    fmt.Println(len(arr)) // 6
    fmt.Println(len(arr)-1) // 5
    fmt.Println(arr[len(arr)-1]) // 6 <- element at index 5 (last element)
    

    【讨论】:

      【解决方案2】:

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

      为了应对空切片——零长度导致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”切片。

      【讨论】:

        【解决方案3】:

        不那么优雅,但也可以:

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

        【讨论】:

        • 这与sl[len(sl)-1:] 相同,但它返回一个包含最后一个元素的slice,而不仅仅是最后一个元素。 play.golang.org/p/kcThrqa-64c
        • @Victor 已经有一段时间没有写这个解决方案了!
        • @ccdrm 并尽量不要硬说,我什至赞成,因为实际上显示了关于该主题的一些有用的东西。问候!
        【解决方案4】:

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

        sl[len(sl)-1]
        

        删除它:

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

        看到这个page about slice tricks

        【讨论】:

        • 非常感谢!尽管看起来很傻,但他们没有添加-1 索引 Python has...
        • 我确实喜欢 Python 中的 -1,尽管它经常会导致难以调试的错误。
        • 他们有意识地把它留在外面。这是不明显的并且容易出错。总体而言,对“太多意义”是谨慎的;它也没有方法/运算符重载、函数参数的默认值等,恕我直言,这在哲学上也很相似。请参阅此讨论和其他讨论:groups.google.com/forum/#!topic/golang-nuts/yn9Q6HhgWi0
        • 我不确定,但我得到了panic: runtime error: index out of range for profiles[len(profiles)-1].UserId,我猜切片的长度是 0 所以它会恐慌?
        • @tom10271 是的,如果没有这样的元素,则无法获取切片的最后一个元素,即。如果根本没有元素。
        猜你喜欢
        • 2018-08-03
        • 2021-12-16
        • 2019-02-02
        • 2014-11-28
        • 2014-05-21
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 2020-04-06
        相关资源
        最近更新 更多