v1.16.12
Added: * slicesx: ** Last ** LastIndex
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user