Skip to content

Inference issue with impl IntoIterator #116246

@clarfonthey

Description

@clarfonthey

I ran into this when trying to refactor some iterators. Here's a minimal reproduction: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c752cb7b8860b49dcf433c69855ff490

enum Either<T: Iterator> { Left(Left<T>), Right(Right<T::Item>), } impl<T: Iterator> Either<T> { fn new(cond: bool, value: impl IntoIterator<IntoIter = T>) -> Either<T> { if cond { Either::Left(Left::new(value)) } else { Either::Right(Right::new(value)) } } } struct Left<T>(T); impl<T: Iterator> Left<T> { fn new(value: impl IntoIterator<IntoIter = T>) -> Left<T> { Left(value.into_iter()) } } struct Right<T>(Vec<T>); impl<T> Right<T> { fn new(value: impl IntoIterator<Item = T>) -> Right<T> { Right(value.into_iter().collect()) } }

I expected this to compile, but instead got this error:

error[E0271]: expected `T` to be an iterator that yields `<impl IntoIterator<IntoIter = T> as IntoIterator>::Item`, but it yields `<T as Iterator>::Item` --> src/lib.rs:10:13 | 10 | Either::Right(Right::new(value)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `std::iter::Iterator::Item`, found `std::iter::IntoIterator::Item` | = note: expected associated type `<T as Iterator>::Item` found associated type `<impl IntoIterator<IntoIter = T> as IntoIterator>::Item` = note: an associated type was expected, but a different one was found For more information about this error, try `rustc --explain E0271`. 

As it says, it's failing to unify these types:

  • <impl IntoIterator<IntoIterator = T>>::Item
  • T::Item

Whereas, these types are required to be the same per the definition of IntoIterator:

pub trait IntoIterator { type Item; type IntoIter: Iterator<Item = Self::Item>; fn into_iter(self) -> Self::IntoIter; }

Meta

Currently fails on latest stable:

rustc 1.72.1 (d5c2e9c34 2023-09-13) binary: rustc commit-hash: d5c2e9c342b358556da91d61ed4133f6f50fc0c3 commit-date: 2023-09-13 host: x86_64-unknown-linux-gnu release: 1.72.1 LLVM version: 16.0.5 

And latest nightly:

rustc 1.74.0-nightly (e7c502d93 2023-09-27) binary: rustc commit-hash: e7c502d9309ae6bc6a9750514ba7fe397844e84c commit-date: 2023-09-27 host: x86_64-unknown-linux-gnu release: 1.74.0-nightly LLVM version: 17.0.0 

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.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