lost.sof
lost.sof

Reputation: 261

Why can I call multiple Option methods that consume self without error?

let option: Option<&str> = None;
// -- unwrap --
let unwrap = panic::catch_unwind(|| option.unwrap());
assert!(unwrap.is_err());
let unwrap_or_default = option.unwrap_or_default();
assert!(unwrap_or_default == "");
let unwrap_or = option.unwrap_or("👌");
assert!(unwrap_or == "👌");
let unwrap_or_else = option.unwrap_or_else(|| "🙌");
assert!(unwrap_or_else == "🙌");

Playground

The methods Option::unwrap_xxx(self) -> T all consume self, so why we can repeatedly call these methods without a compilation error? Isn't the Option moved?

Upvotes: 1

Views: 474

Answers (1)

PitaJ
PitaJ

Reputation: 15084

Rust has the Copy trait which is generally used on small values stored on the stack, like i32, bool, and references. If a type implements Copy, it will be copied instead of moved. Quoting the book:

If a type implements the Copy trait, a variable is still valid after assignment to another variable.

The same applies when passing the variable into a function. The variable will remain valid, as it is copied, not moved.

Copy exists mostly for ergonomics reasons (otherwise explicit .clone() would need to be used too often). And fittingly, Option<T> implements Copy where T implements Copy.

Upvotes: 5

Related Questions