Skip to content

Calling and_then on Option<String> with a function that takes &str could provide a more helpful diagnostic #106342

Closed

Description

@Kampfkarren

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d2e7d8643e1ae76544e6f0f1a117230b

fn produces_string() -> Option<String> {
    Some("my cool string".to_owned())
}

fn takes_str(x: &str) -> Option<()> {
    Some(())
}

fn main() {
    let x = produces_string().and_then(takes_str);
}

The current output is:

error[[E0631]](https://doc.rust-lang.org/stable/error-index.html#E0631): type mismatch in function arguments
  --> src/main.rs:10:40
   |
5  | fn takes_str(x: &str) -> Option<()> {
   | ----------------------------------- found signature defined here
...
10 |     let x = produces_string().and_then(takes_str);
   |                               -------- ^^^^^^^^^ expected due to this
   |                               |
   |                               required by a bound introduced by this call
   |
   = note: expected function signature `fn(String) -> _`
              found function signature `for<'a> fn(&'a str) -> _`
note: required by a bound in `Option::<T>::and_then`

The solution is to change:

-let x = produces_string().and_then(takes_str);
+let x = produces_string().as_deref().and_then(takes_str);

It would be nice if rustc told me this.

Activity

  1. added
    A-diagnosticsArea: Messages for errors, warnings, and lints
    T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
    on Jan 1, 2023
  2. y21 commented on May 14, 2023

    @y21
    Member

    @rustbot claim

  3. added 2 commits that reference this issue on Jun 3, 2023
    ba98957
    91f222f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

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