Skip to content

Confusing compiler error when iterating over Option<IntoIterator> #57872

Open
@KeyboardDanni

Description

@KeyboardDanni

I recently wrote a type that implemented IntoIterator with a tuple as the Item type. I then tried to test this by using this iterator in a for loop. I got the following error:

     for (i, j) in foo
         ^^^^^^ expected struct `MyIter`, found tuple

This left me confused, because I had assumed that foo's type was MyIter. Why was the iterator returning itself, instead of the item type I had specified? I began to suspect my implementation of IntoIterator before I realized that foo was actually Option<MyIter>. As it turns out, Option also implements IntoIterator (#27996), so the compiler thought I was trying to iterate over the Option instead of the enclosed type!

It'd be nice if there were a note associated with the compiler error in cases where the iterator is type Option<T : IntoIterator>. Something like this, maybe?

"Note: `iter` is `Option<MyIter>`. Did you forget to unwrap?"

Simple reproduction of the compiler error:

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=4432a78517e24ea649a31c7246b34edd

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-papercutDiagnostics: An error or lint that needs small tweaks.P-lowLow priorityT-compilerRelevant to the compiler 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