Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
V8031. Using the call of the 'len'...
menu mobile close menu
Additional information
toggle menu Contents

V8031. Using the call of the 'len' function as an index will result in an off-by-one error.

Jun 22 2026

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.