-
-
Notifications
You must be signed in to change notification settings - Fork 14.3k
Closed
Labels
C-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: 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.Relevant to the library API team, which will review and decide on the PR/issue.
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:
unwraprequires full ownership because it moves values- see
selfin signature?
- see
ref_resultis only borrowing, (ref_resultis 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.
werner, lambdalisue and andronat
Metadata
Metadata
Assignees
Labels
C-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: 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.Relevant to the library API team, which will review and decide on the PR/issue.