You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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!
The text was updated successfully, but these errors were encountered:
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
In reality this is more subtle. return is also an expression that returns never type, which will then be coerced into unit type. ↩
The compiler throws an error: "expected
()
, found enumOption
".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!
The text was updated successfully, but these errors were encountered: