The analyzer has detected a potential off-by-one error caused by using the result of the len function as an index. Such an error causes the program to panic.
The code example:
func End(basicLits []*BasicLit) token.Pos {
return basicLits[len(basicLits)].End()
}
Developers wanted to obtain the last element position of the basicLits slice. However, for a n-length slice, valid indices range from 0 to n - 1, so accessing basicLits[len(basicLits)] always results in the program panic.
Fixed code:
func End(basicLits []*BasicLit) token.Pos {
if length := len(basicLits); length > 0 {
return basicLits[length - 1].End()
}
return token.NoPos
}
If a function has a precondition of working with non-zero length slices, then the length > 0 check can be removed.
This diagnostic rule is classified as:
Was this page helpful?
Your message has been sent. We will email you at
If you do not see the email in your inbox, please check if it is filtered to one of the following folders: