Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Options1 question #1357

Closed
Fr3027 opened this issue Feb 6, 2023 · 1 comment
Closed

Options1 question #1357

Fr3027 opened this issue Feb 6, 2023 · 1 comment

Comments

@Fr3027
Copy link

Fr3027 commented Feb 6, 2023

fn maybe_icecream(time_of_day: u16) -> Option<u16> {
    if time_of_day<22{
        Some(5)
    }
    if time_of_day<24{
        Some(0)
    }
    None
}

The compiler throws an error: "expected (), found enum Option".
My point is if any of the conditions match then the function will return Some(), if not, the function will return None by default.
This style is supported by java, which I can't understand why rust not, help me please!

@aleksanderkrauze
Copy link

You can either do

fn maybe_icecream(time_of_day: u16) -> Option<u16> {
    if time_of_day<22{
        return Some(5);
    }
    if time_of_day<24{
        return Some(0);
    }
    None
}

or

fn maybe_icecream(time_of_day: u16) -> Option<u16> {
    if time_of_day<22{
        Some(5)
    } else if time_of_day<24{
        Some(0)
    } else {
        None
    }
}

The compiler even suggests the first solution:

help: you might have meant to return this value
  |
3 |         return Some(5);
  |         ++++++        +

The reason for this is that in rust if statements are expressions. In your example those if branches are unrelated to each other. Therefore rust looks at them in isolation and treats them like statements which must return unit type (). You can solve this in two ways.

You can add return keywords (like compiler suggests, also my first example). This will make if expression return () as they should1.

Or you can combine three branches in one expression (like in my second example). Then each branch of this expression will return Option<u16> so the whole expression will evaluate to Option<u16> and this will be returned from your function.

Footnotes

  1. In reality this is more subtle. return is also an expression that returns never type, which will then be coerced into unit type.

@rust-lang rust-lang locked and limited conversation to collaborators Jul 8, 2024
@mo8it mo8it converted this issue into discussion #2035 Jul 8, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants