snippetgoCritical
How to get the last element of a slice?
Viewed 0 times
lasthowslicetheelementget
Problem
What is the Go way for extracting the last element of a slice?
The solution above works, but seems awkward.
var slice []int
slice = append(slice, 2)
slice = append(slice, 7)
slice[len(slice)-1:][0] // Retrieves the last elementThe solution above works, but seems awkward.
Solution
For just reading the last element of a slice:
For removing it:
See this page about slice tricks
sl[len(sl)-1]For removing it:
sl = sl[:len(sl)-1]See this page about slice tricks
Code Snippets
sl[len(sl)-1]sl = sl[:len(sl)-1]Context
Stack Overflow Q#22535775, score: 484
Revisions (0)
No revisions yet.