Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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?)
    }


Wait! The ? operator works with the `Option<T>` type? I assumed it was only reserved for `Result<T,E>`.


To 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!)


And 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.


But 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


And 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.


It currently works with `Result` and `Option` types, and with RFC#3058 will work with all types implementing the `Try` trait.


Monadic do notation equivalent at that point, I suppose.


Although that would be really fun, the proposed `Try` basically only allows you to call the `Result<_, E>` by a different name.


I 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?


? 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


Well, I guess this counts as a concept I wish I learned earlier!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: