Wong Jia Hau
Wong Jia Hau

Reputation: 3069

How to convert Option<T> to Option<&T> in the most idiomatic way in Rust?

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

Upvotes: 5

Views: 1188

Answers (1)

Wong Jia Hau
Wong Jia Hau

Reputation: 3069

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

Upvotes: 6

Related Questions