The code below can produce a panic if you try to scan the out-of-bounds index:
package main
import "fmt"
func main() {
var numbers []int = []int{1, 2, 3}
var index int
fmt.Scan(&index)
fmt.Println(numbers[index])
}
// Input:
// 3
// Output:
// panic: runtime error: index out of range [3] with length 3
Two conditions provide an out-of-bounds panic:
- it must be an iterable variable;
- an index or the bounds must be set implicitly.
You need to prevent the panic and print the message: "prevented!" if you catch incorrect data.