The "slice bounds out of range" panic occurs when your code attempts to access an index that does not exist in the slice. Add a length check before accessing the element to prevent the panic.
if i < len(mySlice) {
val := mySlice[i]
// use val
} else {
// handle missing index
}
Alternatively, use the slices package helper if you are on Go 1.21+ to safely get a value with a default:
import "slices"
val := slices.IndexFunc(mySlice, func(item Type) bool { return item == target })
if val != -1 {
// found
}
Or simply ensure your loop bounds are correct:
for i := 0; i < len(mySlice); i++ {
// safe access
}