4 ms·
I see, not very familiar with both those idioms `?` and `ok_or()?` My current understanding is that those would return an Error only? I was more describing ca
by vmarsy 8y ago
I see, not very familiar with both those idioms `?` and `ok_or()?`
My current understanding is that those would return an Error only?
I was more describing cases where you do want to return, but not necessarily return an `Error`.
For instance in a simplified example function that returns a boolean, you could decide to return `false`. is it possible there?
// Function that returns a boolean value
fn is_equal_to_ten(n: Option<u32>) -> bool {
// some one liner that checks for None, if it's not none, gives you `x` when `n` matches content of `Some(x)` (not real code):
if let Some(x) = n else { return false; /* what to do in case it's a None*/ }
// `x` is available here:
return (x == 10);
}
Would this be considered bad practice in Rust?
- steveklabnik 8y agoThe question mark operator works via a trait, Try. Both Option and Result implement Try. If you use ? on a None value, it will return None, just like using ? on an Err returns an Err. ok_or is a method on Option that would let you manually convert it to a Result. You could then combine it with ?, turning a None into a specific Err. It won’t help for stuff that returns bool, it’s true.
- vmarsy 8y agoThanks for the detailed answer :)
- Thiez 8y agoOften such functions can be rewritten to perform some operations "inside" the option. For example: fn is_equal_to_ten(n: Option<u32>) -> bool { n.map(|n|n == 10).unwrap_or_default() }