Skip to content

Suggest implementing IntoIterator for &'_ T where T has iter() method returning an iterator (or vice versa) #9736

@Kixunil

Description

@Kixunil

What it does

If the trait implementation is missing it suggests adding it by forwarding to the method (can be automated).
If the trait implementation is present but the inherent method is not suggest adding it forwarding to trait implementation.
Same for mutable versions.

Both of these APIs are idiomatic.

Probably should be only triggered for public T.

Lint Name

impl_iter_into_iterator

Category

style

Advantage

  • The API is idiomatic and intuitive because all types in std and many other crates behave the same
  • It's possible to pass &T to for or functions expecting IntoIterator avoiding typing .iter()

Drawbacks

  • Increases boilerplate in the library

Example

pub struct Foo([u8; 32]);

impl Foo {
    fn iter(&self) -> Iter<'_> { // Iter implements Iterator<Item=&u8>
        Iter::new(&self.0)
    }
}

Could be written as:

pub struct Foo([u8; 32]);

impl Foo {
    fn iter(&self) -> Iter<'_> { // Iter implements Iterator<Item=&u8>
        Iter::new(&self.0)
    }
}

impl<'a> IntoIterator for &'a Foo {
    type IntoIter = Iter<'a>;
    type Item = &'a u8;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

Metadata

Metadata

Assignees

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