191
votes

What is the Go way for extracting the last element of a slice?

var slice []int

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

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

The solution above works, but seems awkward.

3

3 Answers

350
votes

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

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

See this page about slice tricks

0
votes

What is even more awkward is your program crashing on empty slices!

To contend with empty slices -- zero length causing panic: runtime error, you could have an if/then/else sequence, or you can use a temporary slice to solve the problem.

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)
}

which will give you this output:

lastitem: mango
lastitem: none

For []int slices you might want a -1 or 0 for the default value.

Thinking at a higher level, if your slice always carries a default value then the "tmp" slice can be eliminated.

-14
votes

Bit less elegant but can also do:

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