← All lints

mut_generator_rewalked

L0604Performancewarn

Generator holding a mut lend walked twice

a generator called with a mut argument and walked twice

Flagged
fn drain(mut xs: List<Int>) -> yields Int:
    while xs.len > 0:
        yield xs.pop()!
var v = [1, 2, 3]
let g = drain(mut v)
for x in g: print(x)
for x in g: print(x)
Write instead
fn drain(mut xs: List<Int>) -> yields Int:
    while xs.len > 0:
        yield xs.pop()!
var v = [1, 2, 3]
let g = List(drain(mut v))
for x in g: print(x)
for x in g: print(x)

Why

A generator (-> yields T) runs its body again from the top each time it is walked. When it holds a mut lend, the first walk changes what it lends, so the second walk starts from different data: drain(mut v) empties v, and walking it again yields nothing. Copy it once with List(...) if you need the items twice.

The practice it serves

Code that does more work than it needs to.

Not flagged

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

Near miss
fn drain(mut xs: List<Int>) -> yields Int:
    while xs.len > 0:
        yield xs.pop()!
var v = [1, 2, 3]
let g = drain(mut v)
for x in g: print(x)

Turn it off

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

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