Skip to content

into_iter_without_iter false positive when there is a Deref impl #11635

@dtolnay

Description

@dtolnay

Summary

In https://rust-lang.github.io/rust-clippy/master/index.html#/into_iter_without_iter, into_iter_without_iter is motivated by letting users write the simpler val.iter() instead of <&Type>::into_iter(val) or (&val).into_iter().

However, there are cases where a fn iter is not needed in order for .iter() to be available. Namely for a type with a Deref impl, where val.deref().iter() returns the same thing as (&val).into_iter(), the simple val.iter() already works (and will be shown in the documentation by rustdoc). Handwriting a fn iter is needless boilerplate.

Lint Name

into_iter_without_iter

Reproducer

In the following code, clippy wants fn iter so that Thing(...).iter() works. But Thing(...).iter() already works.

#![warn(clippy::pedantic)]

use std::ops::Deref;

pub struct Thing(Vec<u8>);

impl Deref for Thing {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a> IntoIterator for &'a Thing {
    type Item = &'a u8;
    type IntoIter = <&'a [u8] as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}
warning: `IntoIterator` implemented for a reference type without an `iter` method
  --> src/lib.rs:15:1
   |
15 | / impl<'a> IntoIterator for &'a Thing {
16 | |     type Item = &'a u8;
17 | |     type IntoIter = <&'a [u8] as IntoIterator>::IntoIter;
18 | |
...  |
21 | |     }
22 | | }
   | |_^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#into_iter_without_iter
note: the lint level is defined here
  --> src/lib.rs:1:9
   |
1  | #![warn(clippy::pedantic)]
   |         ^^^^^^^^^^^^^^^^
   = note: `#[warn(clippy::into_iter_without_iter)]` implied by `#[warn(clippy::pedantic)]`
help: consider implementing `iter`
   |
15 + 
16 + impl Thing {
17 +     fn iter(&self) -> <&'a [u8] as IntoIterator>::IntoIter {
18 +         <&Self as IntoIterator>::into_iter(self)
19 +     }
20 + }
   |

Version

rustc 1.75.0-nightly (960754090 2023-10-06)
binary: rustc
commit-hash: 960754090acc9cdd2a5a57586f244c0fc712d26c
commit-date: 2023-10-06
host: aarch64-unknown-linux-gnu
release: 1.75.0-nightly
LLVM version: 17.0.2

Additional Labels

No response

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions