Skip to content

Better handling for unwrapping reference to Result (or Option) #48121

Closed
@ghost

Description

Having such simplified code:

fn main() {
    let result: Result<String, String> = Ok("ok".to_string());
    let ref_result = &result;
    let x = ref_result.unwrap();
}

gives:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:4:13
  |
4 |     let x = ref_result.unwrap();
  |             ^^^^^^^^^^ cannot move out of borrowed content

error: aborting due to previous error

error: Could not compile `playground`.

Thanks to irc Kimundi & Amarnath I got the solution & expanation:

// use:
let x = ref_result.as_ref().unwrap();

Explanation:

  • unwrap requires full ownership because it moves values
  • ref_result is only borrowing, (ref_result is a reference, a reference means borrowing)

Using .as_ref() works because:
It creates a brand new Result with references to inner value, like:
from initial:

`&Result<T, V>`

to brand new one:

`Result<&T, &V>`

See implementation of Result.as_ref here

If i got this correctly, using unwrap on &Result will always be corrupted.
My question is, could this be handled internally somehow by Rust?
And/Or better compilation error would be awesome for noobs like me :)
I'm not sure what the message should look like but the current one is a bit general.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API 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