Rust Option Syntax Help

So I'm working through the rustlings course and I'm on option1 and I'm confused why I need to explicitly type return before the Some(5);

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

I was under the impression that returns are implicit in if/else methods. So while I solved the problem I have little understanding of why it works, I only was able to because the compiler basically told me to include the return.

You have misleading indentation:

} if time_of_day

This is a separate if unrelated to previous one. You've probably meant:

} else if time_of_day

Also note that there are no implicit returns in if. if is not special, and it's not really a return.

There is a rule that blocks {} can have a value, and the value is the last expression in the block, like { 1; 2 } the value is 2. This works for blocks in blocks too, e.g. { 1; { 2 } }.

Last expression in the function can be the function's return value, and if {} else {} is an expression.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.