Skip to content

Recommend Option::as_deref when given Option<&String> in place of Option<&str> #89856

Closed
@NoraCodes

Description

@NoraCodes

&String can easily be converted to &str, but we give a somewhat opaque E0308 when faced with the following situation:

fn take_str_maybe(x: Option<&str>) -> Option<&str> { None }

fn main() {
    let string = String::from("Hello, world");
    let option = Some(&string);
    take_str_maybe(option);
}

This results in:

error[E0308]: mismatched types
 --> src/main.rs:8:20
  |
8 |     take_str_maybe(option);
  |                    ^^^^^^ expected `str`, found struct `String`
  |
  = note: expected enum `Option<&str>`
             found enum `Option<&String>`

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

playground

Which is not totally clear to people who do not understand the Deref trait and/or do not know that it is implemented for these types.

We should suggest that the user use Option::as_deref to convert between these types.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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