Best Syntax For De-Ref'ing A Thing In An Option?

Hi, I have a function that returns an option of a u32.

I am using some library function that returns <Option<&u32>>

Current code (setting a field on an instance of a struct that is about to be returned by the fn):

flag: matches.get_one::<u32>(&FLAG_NAME),

But I have the error:
" mismatched types
expected enum Option<u32>
found enum Option<&u32>rustc[Click for full compiler diagnostic], 53): use Option::copied to copy the value inside the Option: .copied()

View Problem (⌥F8)

Quick Fix... (⌘.)"

So I then wrote a match expression like this:

flag: match matches.get_one::<u32>(&FLAG_NAME) {
    Some(flag) => Some(*flag),
    None => None,

This works, but it seems like an awfully lot of code to accomplish what I need. Is there any nice one liner syntax I could use here? :thinking:

In the error message :wink:

(BTW, the opposite operation is as_ref() or as_deref() depending on whether you need deref coercion or not.)

1 Like

actually, the original doesn't work... I get the error, "Could not downcast to u32, need to downcast to alloc::string::String'

how to I actually use Option::copied though? by calling .as_deref() on the option?

You can just call .copied()