How to get the last element of a slice?
If you can use Go 1.18 or above and you often need to access the last element of a slice of some arbitrary element type, the use of a small custom function can improve readability at call sites:
package main
import "fmt"
func Last[E any](s []E) (E, bool) {
if len(s) == 0 {
var zero E
return zero, false
}
return s[len(s)-1], true
}
func main() {
var numbers []int
fmt.Println(Last(numbers)) // 0 false
numbers = []int{4, 8, 15, 16, 23, 42}
fmt.Println(Last(numbers)) // 42 true
}
(Playground)
No need to create a library for that Last
function, though; a little copying is better than a little dependency.
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