Closed

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- see
self
in signature?
- see
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.