← All lints

peek_then_pop

L0525Idiomswarn

Peek then pop

let x = s.last! then s.pop(): let x = s.pop()! takes it

Flagged
var stk = [1, 2, 3]
var sum = 0
for _ in 0..2:
    let u = stk.last!
    stk.pop()
    sum += u
print(sum, stk.len)
Write instead
var stk = [1, 2, 3]
var sum = 0
for _ in 0..2:
    let u = stk.pop()!
    sum += u
print(sum, stk.len)

Why

C++ reads a stack with .back() and then drops it with .pop_back(), because pop_back returns nothing. A CP Lang List.pop() returns the element it takes (None when empty), so let x = s.last! followed by s.pop() is one step: let x = s.pop()!. Both trap on an empty list. The fix applies when the list is a plain name or field path whose type is List, and nothing stands between the two lines.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: H. C++ habits.

Not flagged

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

Near miss
var stk = [1, 2, 3]
var sum = 0
for _ in 0..2:
    let u = stk.last!
    sum += u
    stk.pop()
print(sum, stk.len)

Turn it off

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

Generated from spec/lints/peek_then_pop, the same record the linter is built from.