Reputation: 215117
New to rust here and trying to learn. Consider the following piece of code:
let x = Some("air");
println!("{}", x.unwrap());
println!("{}", x.unwrap());
Why does this work? Because the unwrap
method has the following signature pub fn unwrap(self) -> T
, so it should move self
into the method, which means after the first call of x.unwrap
, I shouldn't be able to access x
anymore. However this still works? Can someone explain what misunderstanding I am taking here?
Upvotes: 1
Views: 1544
Reputation: 10733
You are confusing &str
with String
, which rather is not Copy
.
fn main() {
// This will work fine.
let x = Some("data");
println!("{:?}", x.unwrap());
println!("{:?}", x.unwrap());
// however, this will generate an error since value will be moved.
let x = Some("data".to_string());
println!("{:?}", x.unwrap());
println!("{:?}", x.unwrap());
}
Upvotes: 9
Reputation: 215117
Just figured out, x
in OP is not moved because Option<&str>
implements the Copy
trait. On the other hand if the inner type in the option is a more complex type for instance a struct
, this wouldn't work:
struct Node<T> { elem: T }
let y = Some(Node { elem: 3});
println!("{}", y.unwrap().elem);
println!("{}", y.unwrap().elem);
will give the following error:
Line 33, Char 24: use of moved value: `y` (solution.rs) | 32 | println!("{}", y.unwrap().elem); | - value moved here 33 | println!("{}", y.unwrap().elem); | ^ value used here after move |
Upvotes: 2
Reputation: 2397
The unwrap()
method is used to remove the parent element from the selected element and not the element itself.
Lets say Y
is parent for 'X' and 'Z' is parent of 'Y' then when you say x.unwrap()
X's parent 'Y' is removed and 'Z' becomes the parent of 'X' and now when you say x.unwrap()
again then 'Z' is removed.
Upvotes: -2