So I'm looking at the impl for is_some() for Option and I noticed that it uses match *self {} under the hood...so it moves it internally.
My question is, if it gets moved, how am I able to do something like this? https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f094da12290b77bad526674467e51043
fn main() {
let x = Option::Some(3);
x.is_some();
x.is_some();
}
My expectation is that I should be able to call is_some() only once, and the next time I call it I should get some sort of error saying it's been moved...but no, it all compiles fine.
What am I misunderstanding?
*self in match *self { ... } does not move (or copy) what self points to. From "The Rust Reference" (emphasis mine),
A
matchbehaves differently depending on whether or not the scrutinee expression is a place expression or value expression. If the scrutinee expression is a value expression, it is first evaluated into a temporary location, ...When the scrutinee expression is a place expression, the match does not allocate a temporary location; however, a by-value binding may copy or move from the memory location. ...
*self is a place expression. From "The Rust Reference" (emphasis mine),
Expressions are divided into two main categories: place expressions and value expressions. ...
A place expression is an expression that represents a memory location. These expressions are paths which refer to local variables, static variables, dereferences (
*expr), array indexing expressions (expr[expr]), field references (expr.f) and parenthesized place expressions. All other expressions are value expressions.A value expression is an expression that represents an actual value.
You might also be interested to know that the Some(_) => true arm in the match body does not bind anything. From "The Rust Reference",
Unlike identifier patterns, it does not copy, move or borrow the value it matches.
where "it" means the wildcard pattern (_).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With