Reputation: 1825
I have function that looks like this:
pub fn new(s: String) -> Option<i32> {
if s.len() > 10 {
None
}
Some(10)
}
When I try to compile this, I get following error message:
7 | / if s.len() > 10 {
8 | | None
| | ^^^^ expected `()`, found enum `std::option::Option`
9 | | }
| | -- help: consider using a semicolon here
| |_________|
| expected this to be `()`
|
= note: expected unit type `()`
found enum `std::option::Option<_>`
I am not sure what I am doing wrong. Any help would be appreciated
Upvotes: 4
Views: 9953
Reputation: 4133
No ;
Returns can only be used at the end of a block.
To fix this you can either:
pub fn new(s: String) -> Option<i32> {
if s.len() > 10 {
return None; // Add a early return here
}
Some(10)
}
Or
pub fn new(s: String) -> Option<i32> {
if s.len() > 10 {
None
} else {
Some(10)
} // This is now the end of the function block.
}
Upvotes: 8