Skip to content

Commit

Permalink
Add safe sliceget function
Browse files Browse the repository at this point in the history
  • Loading branch information
unitoftime committed Feb 17, 2025
1 parent 17f5b5b commit d98b521
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions ds/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,12 @@ func GrowAdd[K any](slice []K, idx int, val K) []K {
slice[idx] = val
return slice
}

// Safely gets and returns a value from a slice, and a boolen to indicate boundscheck
func SafeGet[K any](slice []K, idx int) (K, bool) {
if idx < 0 || idx >= len(slice) {
var k K
return k, false
}
return slice[idx], true
}

0 comments on commit d98b521

Please sign in to comment.