rust-lang / rust-lang/rust

Misleading error message - Returning Option<T> when Clone not implemented

Open
#136,151 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics D-terse T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

When a function returns Option<T> and the function is basically a wrapper on an Arc<RwLock<Option<T>>> but T does not implement Clone then the code self.value.read().unwrap().as_ref().map(|value| value.clone()) will show a compile error "mismatched types" as the return type is Option<_> and found Option<&_>. This suggests that I need to clone the value, but I am already doing that. Trying to dereference the value also fails with the error that the T does not implement Copy (nor do I want it to).

Example:

struct MyStruct<T>
{
    value: Arc<RwLock<Option<T>>>,
}

impl<T> MyStruct<T>
{
    fn get_value(&self) -> Option<T> {
        let locked_value = self.value.read().unwrap();
        locked_value.as_ref().map(|value| value.clone())
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9ab38c00a0a33a5c07b2aa42fa510762

I expected to see this happen:
The underlying issue of "no method named clone found for type" is the true underlying problem that is hidden from the developer.

Instead, this happened:
I was misdirected to the return type being invalid.

I was under the impression that bad or misleading error messages in Rust are considered bugs, but if that is not the case please let me know what I need to do to help resolve this issue. Thank you.

Edit:
While constructing the more complete example, I noticed that omitting the .as_ref() then caused the compiler to properly call out the lack of Clone. When I added T: Clone then an error would appear since I was missing .as_ref(). This bug demonstrates that if you already start with .as_ref() included, that the compiler fails to point you to the lack of Clone.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Rust Playground and the minimal MyStruct example, comparing diagnostics with and without .as_ref() and with T: Clone. The fix is done when the compiler points developers to the missing Clone implementation instead of only reporting the mismatched return type.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.