Skip to content

Using flat_map on an Option<T> should suggest using and_then instead #108437

Description

@liquidev

Code

fn main() {
    let opt = Some(1);
    opt.flat_map(|val| Some(val));
}

Current output

error[E0599]: `Option<{integer}>` is not an iterator
 --> src/main.rs:3:9
  |
3 |     opt.flat_map(|val| Some(val));
  |         ^^^^^^^^ `Option<{integer}>` is not an iterator
 --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:518:1
  |
  = note: doesn't satisfy `Option<{integer}>: Iterator`
  |
  = note: the following trait bounds were not satisfied:
          `Option<{integer}>: Iterator`
          which is required by `&mut Option<{integer}>: Iterator`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `playground` due to previous error

Desired output

error[E0599]: `Option<{integer}>` is not an iterator
 --> src/main.rs:3:9
  |
3 |     opt.flat_map(|val| Some(val));
  |         ^^^^^^^^
  |         | `Option<{integer}>` is not an iterator
  |         = help: if you wish to map and flatten the option, use `and_then`
 --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:518:1
  |
  = note: doesn't satisfy `Option<{integer}>: Iterator`
  |
  = note: the following trait bounds were not satisfied:
          `Option<{integer}>: Iterator`
          which is required by `&mut Option<{integer}>: Iterator`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `playground` due to previous error

Rationale and extra context

I've run into this confusing naming issue time and time again and I think the compiler could provide a more helpful error message in this case, hinting that you should use and_then instead of flat_map if you wish to do the same operation on options (which you could write as .map().flatten(), hence why I always think it's Option::flat_map and not Option::and_then.)

Other cases

No response

Anything else?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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