Skip to content

unused-peekable can trigger when peek() is used #9456

Closed
@trinity-1686a

Description

@trinity-1686a

Summary

In some cases unused-peekable triggers when having a Peekable<_> is required to satisfy the interface of some other function

Lint Name

unused-peekable

Reproducer

I tried this code:

use std::iter::Peekable;

struct PauseAt<'a, I: Iterator> {
    peek: &'a mut Peekable<I>,
}

impl<'a, I: Iterator> PauseAt<'a, I> {
    fn from_peekable(peek: &'a mut Peekable<I>) -> Self
    {
        PauseAt {
            peek,
        }
    }
    fn peek(&mut self) -> Option<&I::Item> {
        self.peek.peek()
    }
}

fn main() {
    let mut iter = (1..10).into_iter().peekable();

    let mut iter = PauseAt::from_peekable(&mut iter);
    assert_eq!(iter.peek(), Some(&1)); // we can do this multiple times,
    assert_eq!(iter.peek(), Some(&1)); // but count isn't advanced.
}

I saw this happen:

$> cargo +nightly clippy -- -D clippy::unused-peekable
    Checking testing v0.1.0 (/tmp/testing)
error: `peek` never called on `Peekable` iterator
  --> src/main.rs:20:13
   |
20 |     let mut iter = (1..10).into_iter().peekable();
   |             ^^^^
   |
   = note: requested on the command line with `-D clippy::unused-peekable`
   = help: consider removing the call to `peekable`
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable

error: could not compile `testing` due to previous error

I expected to see this happen:

No error: having a Peekable is required to satisfy PauseAt::from_peekable interface (and peek() is called, indirectly)

Version

rustc 1.65.0-nightly (1d37ed661 2022-09-09)
binary: rustc
commit-hash: 1d37ed661a6922e7a167609b8cd7eb31e972b19b
commit-date: 2022-09-09
host: x86_64-unknown-linux-gnu
release: 1.65.0-nightly
LLVM version: 15.0.0

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    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