Skip to content

Bad diagnostics using ? operator on Option<Cow<'_, str>> [E507] #116335

Closed as not planned
@djc

Description

@djc

Code

use std::borrow::Cow;

struct Foo<'a> {
    list: Vec<Bar<'a>>,
}

impl<'a> Foo<'a> {
    fn bar(&self) -> Option<String> {
        Some(self.list.first()?.inner?.into_owned())
    }
}

struct Bar<'a> {
    inner: Option<Cow<'a, str>>,
}

Current output

error[E0507]: cannot move out of a shared reference
 --> src/lib.rs:9:14
  |
9 |         Some(self.list.first()?.inner?.into_owned())
  |              ^^^^^^^^^^^^^^^^^^^^^^^^-
  |              |
  |              value moved due to this method call
  |              move occurs because value has type `Option<Cow<'_, str>>`, which does not implement the `Copy` trait
  |
note: `branch` takes ownership of the receiver `self`, which moves value
 --> /rustc/d5c2e9c342b358556da91d61ed4133f6f50fc0c3/library/core/src/ops/try_trait.rs:217:15
help: you can `clone` the value and consume it, but this might not be your desired behavior
  |
9 |         Some(clone().self.list.first()?.inner?.into_owned())
  |              ++++++++

For more information about this error, try `rustc --explain E0507`.

Desired output

No response

Rationale and extra context

Pointing to some anonymous branch() method from (what I presume is) an impl for Try feels very unhelpful here. Note also the strange suggestion which wants me to add a bare clone() call before the expression...

Other cases

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-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