← All lints

literal_slice_index

L0605Correctnesswarn

Literal index into a slice

w[0] on a slice that keeps its source's keys: w.first! or w.nth(0)

Flagged
let xs = [4, 5, 6, 7]
let w = xs[1..3]
print(w[1])
Write instead
let xs = [4, 5, 6, 7]
let w = xs[1..3]
print(w.nth(0))

Why

A slice keeps its source's keys (R04b): w = xs[1..3] is indexed by 1 and 2, so w[1] is xs[1], the first item, and w[0] is out of range. C++ and Python count a subarray from 0; CP Lang does not, so the same index can never mean two things. Read by position with w.nth(k) or w.first!, walk it with for x in w, or call w.rebase to count from 0.

The practice it serves

Code that is wrong or almost certainly a bug. Denied by cpl lint.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let xs = [4, 5, 6, 7]
let w = xs[1..3]
for x in w: print(x)

Turn it off

For one block, wrap it in with lint(literal_slice_index: allow):. For a project, add literal_slice_index = "allow" under [lints] in cp.toml.

Generated from spec/checker-lints/literal_slice_index, the same record the linter is built from.