Skip to content

Incorrect trait bound handling for IntoIterator<IntoIter = I, Item = T> #137185

Open
@DJDuque

Description

@DJDuque

I tried this code:

pub struct Positive<F>(F);

struct MyStruct<F, I> {
    first: Option<F>,
    iter: I,
}

impl<F, I> MyStruct<F, I> {
    fn new<T>(iter: T) -> Self
    where
        T: IntoIterator<IntoIter = I, Item = Positive<F>>,
    {
        let mut iter = iter.into_iter();
        let first = iter.next().map(|Positive(t)| t);
        
        Self { iter, first }
    }
}

I expected it to compile just like this does:

pub struct Positive<F>(F);

struct MyStruct<F, I> {
    first: Option<F>,
    iter: I,
}

impl<F, I> MyStruct<F, I> {
    fn new<T>(iter: T) -> Self
    where
        T: IntoIterator<IntoIter = I>,
        I: Iterator<Item = Positive<F>>,
    {
        let mut iter = iter.into_iter();
        let first = iter.next().map(|Positive(t)| t);
        
        Self { iter, first }
    }
}

Instead, it complains:

error[E0599]: no method named `next` found for type parameter `I` in the current scope
  --> src/main.rs:15:26
   |
8  | impl<F, I> MyStruct<F, I> {
   |         - method `next` not found for this type parameter
...
15 |         let first = iter.next().map(|Positive(t)| t);
   |                          ^^^^ method not found in `I`
   |
   = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `next`, perhaps you need to restrict type parameter `I` with it:
   |
8  | impl<F, I: Iterator> MyStruct<F, I> {
   |          ++++++++++

Meta

rustc --version --verbose:

~> rustc --version --verbose
rustc 1.82.0 (f6e511eec 2024-10-15)
binary: rustc
commit-hash: f6e511eec7342f59a25f7c0534f1dbea00d01b14
commit-date: 2024-10-15
host: x86_64-unknown-linux-gnu
release: 1.82.0
LLVM version: 19.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemC-bugCategory: This is a bug.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions