Skip to content

Diagnostic for comparison between Option<&str> and Option<String> suggests unconditional allocation #102063

Open
@Sciencentistguy

Description

@Sciencentistguy

Given the following code:

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=79254307273b4f3879568ed37ef40f43

fn main() {
    let variable = Some(String::from("hello world"));
    if variable == Some("hello world") {
        println!("Hi!");
    }
}

The current output is:

error[[E0308]](https://doc.rust-lang.org/nightly/error-index.html#E0308): mismatched types
 --> src/main.rs:3:25
  |
3 |     if variable == Some("hello world") {
  |                    ---- ^^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
  |                    |    |
  |                    |    expected struct `String`, found `&str`
  |                    arguments to this enum variant are incorrect
  |
note: tuple variant defined here

I think a better suggestion would be to use Option::as_deref() or similar here, rather than unconditionally allocating a new string.

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