Skip to content

needless_lifetimes wrongly detect elidable lifetime with Iterator #11291

Closed
@mgautierfr

Description

@mgautierfr

Summary

Clippy wrongly detect a lifetime which could be elided.

Lint Name

needless_lifetimes

Reproducer

I tried this code:

use std::collections::HashMap;

pub struct MyContainer(HashMap<u8, u32>);

impl MyContainer {
    pub fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a u8, &'a u32)> + 'a {
        self.0.iter()
    }
}

I saw this happen:

warning: the following explicit lifetimes could be elided: 'a
 --> test_clippy.rs:6:5
  |
6 |     pub fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a u8, &'a u32)> + 'a {
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
  = note: `#[warn(clippy::needless_lifetimes)]` on by default
help: elide the lifetimes
  |
6 -     pub fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a u8, &'a u32)> + 'a {
6 +     pub fn iter(&self) -> impl Iterator<Item = (&'_ u8, &'a u32)> + 'a {
  |

warning: 1 warning emitted

I expected to see this happen:

Lifetime 'a cannot be elided. Clippy should not emit a warning.

Version

`clippy-driver -V` : `clippy 0.1.73 (8131b97 2023-08-02)`

`rustc -Vv` : 

rustc 1.73.0-nightly (8131b9774 2023-08-02)
binary: rustc
commit-hash: 8131b9774ebcb6c162fcac71545a13543ec369e7
commit-date: 2023-08-02
host: x86_64-unknown-linux-gnu
release: 1.73.0-nightly
LLVM version: 16.0.5


### Additional Labels

_No response_

<!-- TRIAGEBOT_START -->

<!-- TRIAGEBOT_ASSIGN_START -->

<!-- TRIAGEBOT_ASSIGN_DATA_START$${"user":"PartiallyTyped"}$$TRIAGEBOT_ASSIGN_DATA_END -->

<!-- TRIAGEBOT_ASSIGN_END -->
<!-- TRIAGEBOT_END -->

Metadata

Metadata

Labels

C-bugCategory: Clippy is not doing the correct thingI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions