4 ms·
You do get better about using the functional operators as you use them, and they can be incredibly powerful and convenient in certain operations, but in this ca
by jxcl 4y ago
You do get better about using the functional operators as you use them, and they can be incredibly powerful and convenient in certain operations, but in this case he's missing the simplest implementation of this function using the `?` operator:
fn add2(x: Option<i32>, y: Option<i32>) -> Option<i32> {
Some(x? + y?)
}
- deleted 4y ago[deleted]
- bkolobara 4y agoWait! The ? operator works with the `Option<T>` type? I assumed it was only reserved for `Result<T,E>`.
- misnome 4y agoI also (written a few tools in rust, dabble now and then) was under the impression that it only worked with Result. Is this recent or just never encountered?
- deleted 4y ago[deleted]
- steveklabnik 4y ago? is able to be used with Option as of Rust 1.22, released in November of 2017 https://blog.rust-lang.org/2017/11/22/Rust-1.22.html https://blog.rust-lang.org/2017/11/22/Rust-1.22.html
- misnome 4y agoWell, I guess this counts as a concept I wish I learned earlier!
- yccs27 4y agoIt currently works with `Result` and `Option` types, and with RFC#3058 will work with all types implementing the `Try` trait.
- satvikpendem 4y agoMonadic do notation equivalent at that point, I suppose.
- yccs27 4y agoAlthough that would be really fun, the proposed `Try` basically only allows you to call the `Result<_, E>` by a different name.
- steveklabnik 4y agoTo slightly elaborate on yccs27's good answer, at the moment, you can use ? for both Option<T> and Result<T, E>, but you can only use them in functions that return the same type, that is fn can_use_question_mark_on_option() -> Option<i32> { fn can_use_question_mark_on_result() -> Result<i32, ()> { if you have them mixed in the body, they won't work directly. What you should/can do there depends on specifics. For example, if you have a function that returns Option and you have a Result inside, and you want any E to turn into None, you can add .ok() before the ? and then it still looks nice. (The compiler will even suggest this one!)
- pavon 4y agoAnd an even smaller caveat: If you use older (distro provided) Rust versions note that it may look like there is some partial implementation of allowing mixing with NoneError, etc. Ignore this. It doesn't work, and was removed in later versions.
- nicoburns 4y agoBut also: don't use your distro provided version of Rust. It's intended for compiling distro packages that depend on Rust, not for developing with Rust. Get Rust from https://rustup.rs https://rustup.rs
- pavon 4y agoAnd hence for writing rust code you would like to package for your distro of choice. I publish my software because I want others to use it, and including it in distro repos is the most friendly way to do that.