4

Suppose I have a value x that has the type of Option<T>, how do I convert it to Option<&T> ?
I tried using map:

let result = x.map(|x| &x)
                       ^^ Error

But I got the error:

cannot return reference to function parameter `x`
returns a reference to data owned by the current function
Wong Jia Hau
  • 2,639
  • 2
  • 18
  • 30
  • 2
    Related: [How to borrow an unwrapped Option?](https://stackoverflow.com/questions/51385381/how-to-borrow-an-unwrapped-optiont) – Sven Marnach Feb 01 '21 at 10:26
  • Does this answer your question? [Cannot move out of value which is behind a shared reference when unwrapping](https://stackoverflow.com/questions/32338659/cannot-move-out-of-value-which-is-behind-a-shared-reference-when-unwrapping) – pretzelhammer Feb 01 '21 at 12:54
  • @pretzelhammer No it does not, although the solution looks similar, I believe it's a totally different question. I'm specifically asking how to convert Option to Option<&T>, even the error thrown is phrased differently. Therefore I request that this question to be opened again. – Wong Jia Hau Feb 01 '21 at 13:06

1 Answers1

5

After some trial and error, I found the method, which is as_ref.

Reference: https://doc.rust-lang.org/std/option/enum.Option.html#method.as_ref

Wong Jia Hau
  • 2,639
  • 2
  • 18
  • 30