Skip to content

Options1 question #2035

Closed Answered by aleksanderkrauze
Fr3027 asked this question in Q&A
Discussion options

You must be logged in to vote

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 tr…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by mo8it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #1357 on July 08, 2024 12:55.