Skip to content

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

@Kampfkarren

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.

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