A panic interrupts ordinary control flow when something has gone seriously wrong. Go can trigger one at runtime: indexing a slice past its length stops the program and reports an index-out-of-range error. Code can also call panic(any) to report a value and provide a code path to the call. section 4.2.8 section 7.4
Prevent predictable panics rather than using them for routine error handling. If a function requires three slice entries, check len before indexing and return an error when the requirement is unmet. If it can accept any number of entries, a range loop avoids those fixed indices altogether. section 4.2.8
Missing command-line argument
os.Args includes the program name, so reading os.Args[1] without an additional argument panics. Check `len(os.Args) < 2` first; then report that a filename is needed instead of attempting the invalid access. section 2.7.2
Reserve an explicit panic for a truly exceptional condition that cannot reasonably be handled without terminating the program. If callers might encounter the condition, return an error instead. Document any deliberate panic in the function’s godoc comment. recover may contain a sporadic panic temporarily, but finding and fixing its cause is usually the better response. section 7.12.1 section 7.13
Listing 4.59 Using a range statement Instead of explicit indices
func printMedalists3(raceName string, contestants []string) {
fmt.Printf("Results for %s:\n", raceName)
for place, contestant := range contestants {
switch place {
case 0:
fmt.Printf("Gold Medal: %s\n", contestant)
case 1:
fmt.Printf("Silver Medal: %s\n", contestant)
case 2:
fmt.Printf("Bronze Medal: %s\n", contestant)
default:
fmt.Printf("Finisher: %s\n", contestant)
// or just return
}
}
}
func main() {
race1 := []string{"Sally", "Steve", "Jo", "Adam"}
race2 := []string{"Jon", "Jen"}
race3 := []string{}
printMedalists3("Race 1", race1)
// Race 2 only has two contestants, but we still need to list them!
printMedalists3("Race 2", race2)
// Throw in a race with no contestants at all.
printMedalists3("Race 3", race3)
}
The range-based race-results function handles short and empty slices without indexing entries that might not exist. section 4.2.8







