Skip to content

Prefer .iter() to implicit IntoIterator impl of &(mut) {Collection} #8585

Open
@pitaj

Description

@pitaj

Essentially, the opposite of explicit_iter_loop

What it does

This lint would forbid cases where the IntoIterator impl for a reference to a collection is used, and recommend using the .iter() or .iter_mut() associated function instead.

Lint Name

implicit_iter_loop

Category

restriction

Advantage

  • Readability
  • More explicit
  • Easier to reason about
  • More refactor friendly .iter() -> .iter_mut() or .iter().enumerate(), etc
  • Works consistently on owned values and references at any indirection level:
let v = vec![1u8];
let r = &v;
let rr = &&v;

for x in v.iter() {}
for x in r.iter() {}
for x in rr.iter() {}

for x in v {} // not a reference iterator
for x in rr {} // error: `&&Vec<u8>` is not an iterator

Drawbacks

  • More verbose
  • Disagreement on whether this is idiomatic

Example

let v = vec![0u8];
for ref_to_elem in &v { }

can be rewritten to

let v = vec![0u8];
for ref_to_elem in v.iter() {}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions