3 ms·
I wish Option and Result weren’t exclusive. Sometimes a method can return an error, no result or a valid result. Some crates return an error for “no result”, wh
by dabinat 1y ago
I wish Option and Result weren’t exclusive. Sometimes a method can return an error, no result or a valid result. Some crates return an error for “no result”, which feels wrong to me. My solution is to wrap Result<Option>, but it still feels clunky.
I could of course create my own type for this, but then it won’t work with the ? operator.
- vjerancrnjak 1y agoThis sounds valid. Lookup in a db can be something or nothing or error. Just need a function that allows lifting option to result.
- dicytea 1y ago> I could of course create my own type for this, but then it won’t work with the ? operator. This is what the Try[^1] trait is aiming to solve, but it's not stabilized yet. [^1]: https://rust-lang.github.io/rfcs/3058-try-trait-v2.html https://rust-lang.github.io/rfcs/3058-try-trait-v2.html
- atoav 1y agoI think Result<Option> is the way to go. It describes precisely that: was it Ok? if yes, was there a value? I could imagine situations where an empty return value would constitute an Error, but in 99% of cases returning None would be better. Result<Option> may feel clunky, but if I can give one recommendation when it comes to Rust, is that you should not value your own code-aesthetical feelings too much as it will lead to a lot of pain in many cases — work with the grain of the language not against it even if the result does not satisfy you. In this case I'd highly recommend just using Result<Option> and stop worrying about it. You being able to compose/nest those base types and unwraping or matching them in different sections of your code is a strength not a weakness.
- Arnavion 1y agoResult<Option> is the correct way to represent this, and if you need further convincing, libstd uses it for the same reason: https://doc.rust-lang.org/stable/std/primitive.slice.html?search=-%3E%20Result%3COption%3E https://doc.rust-lang.org/stable/std/primitive.slice.html?se...
- estebank 1y agoFor things like this I find that ? still works well enough, but I tend to write code like match x(y) { Ok(None) => "not found".into(), Ok(Some(x)) => x, Err(e) => handle_error(e), } Because of pattern matching, I often also have one arm for specific errors to handle them specifically in the same way as the ok branches above.
- 0x457 1y agoWell, I think returning "not found" when action performed was an "update X" and X doesn't exist. Result<Option> is totally normal where it makes sense, tho.