72af113204
Added: * slicesx: ** Last ** LastIndex
44 lines
553 B
Go
44 lines
553 B
Go
package slicesx
|
|
|
|
/*
|
|
Last returns the last item/element in slice s.
|
|
|
|
e will be the nil/zero value of the slice element type
|
|
if the slice length is 0.
|
|
*/
|
|
func Last[S ~[]E, E any](s S) (e E) {
|
|
|
|
var idx int = LastIndex(s)
|
|
|
|
if idx < 0 {
|
|
return
|
|
}
|
|
|
|
e = s[idx]
|
|
|
|
return
|
|
}
|
|
|
|
/*
|
|
LastIndex returns the index of the last element in slice s.
|
|
|
|
If s is empty, idx will be -1.
|
|
If s is nil, idx will be -2.
|
|
*/
|
|
func LastIndex[S ~[]E, E any](s S) (idx int) {
|
|
|
|
var l int = len(s)
|
|
|
|
idx = -2
|
|
if s != nil {
|
|
idx++
|
|
}
|
|
if l == 0 {
|
|
return
|
|
}
|
|
|
|
idx = l - 1
|
|
|
|
return
|
|
}
|