Help me understand the move of Option<&T>?

The rust playground link: Rust Playground

From the rust doc, the <Option>.map method will consume the self, so in the following code:

let text: Option<String> = Some("hello".to_owned());
let _text_length_2 =|s| s.len());

I understand that text's ownership of it's original resource has gone, I can not use text variable anymore.

If I want to use text in the following code, I have to use as_ref method to convert Option<T> to Option<&T>:

// this code works fine.

let text: Option<String> = Some("hello".to_owned());

let text_ref = text.as_ref();
let _text_length =|s| s.len());
println!("{:?}", text_ref);

My question is, why text_ref is not moved(ownership transfered somewhere)? is it because &T is Copy so Option<&T> is Copy too ?? So rust doesn't move something that is Copy?

1 Like

Both copying and moving are bitwise copies. After the bitwise copy:

  • If the original type was Copy, then the original value is not invalidated and is still available for use (that's what you're seeing here), and the original value is considered to have been copied.
  • If the original type is not Copy, the original value is considered moved (i.e. it's ownership is transferred) and is no longer accessible at the original binding.

You can answer this question yourself by reading the relevant documentation:

impl<T> Copy for Option<T>
    T: Copy

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.