How to get the last element of a slice?

Morgan Wilde picture Morgan Wilde · Mar 20, 2014 · Viewed 128.4k times · Source

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.

Answer

Toni Cárdenas picture Toni Cárdenas · Mar 20, 2014

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