Convert Result to Some or None if its checked

The idea is for removing unnecessary code in rust.

Example:

let option_1 = Option::Some(1);

if option_1.is_none() {
    return Ok(());
}

let option_1 = option_1.unwrap();

After checking if option is none i still need to unwrap etc to get the value. But i for sure know that option must be Some and never can be None. Why not automatically convert it to some?

Because flow typing is hard.

6 Likes

Because that changes the type and things don't just change the type. You can however change your code:

let option_1 = match option_1 {
  None => return Ok(()),
  Some(o) => o,
};

or depending on your code structure:

if let Some(o) = option_1 {
    // use `o` in here.
}
6 Likes

Or let Some(value) = option_1 else { return ... }

8 Likes

Note that there's already routes to do this:

let option_1 = Option::Some(1);

if let Some(one) = option_1 {
    // In here, `one` is the contained value
} else {
    Ok(())
}

or

let option_1 = Option::Some(1);

let Some(option_1) = option_1 else { return Ok(()) };

You can also use is_none and unwrap as in your post, or restructure so that an Err return is expected and then use option_1.ok_or(error)? to return Err(error) if the Option contains a None, not Some(_).

All of these options mean that there's no huge value to being able to do what you describe - but it does add a lot of complexity to the compiler.

And note that with the code you've written, the compiler is able to optimize out the unwrap because it can see that the value is always None. This is not guaranteed, but it's an optimization that I'd expect to see fire more often than not.

3 Likes

Indeed, it's even rust that optimizes this out, as you can see in https://rust.godbolt.org/z/YPKfsWaWa.

It's not dependent on LLVM understanding what's going on, which makes it even more likely that it would continue optimizing out going forward.

3 Likes

nitpick, it's rustc that performs the optimization, not the rust language, that performs the optimization, an alternative compiler like mrustc would not neccarily do this (compare this to the null pointer optimization with Option, which is guaranteed by the language)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.