Explicit indexing operations should be carefully vetted; there could be logical errors leading to index out-of-bounds access and then runtime panic.
If the operation uses a variable index but checks the length against a constant, it is risky. Hence, the length should be compared to the index instead.
func hasPrefix(s, prefix []int) bool {
for i := 0; i < len(prefix); i++ {
if len(s) == 0 || prefix[i] != s[i] { // Logical error, try `len(s) <= i`.
return false
}
}
return true
}
func hasPrefix(s, prefix []int) bool {
for i := 0; i < len(prefix); i++ {
if len(s) <= i || prefix[i] != s[i] { // Logical error, try `len(s) <= i`.
return false
}
}
return true
}