Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected unit type '()', found 'enum std::option::Option'

Tags:

rust

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

like image 935
Ach113 Avatar asked Nov 02 '25 11:11

Ach113


1 Answers

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.
}
like image 179
8176135 Avatar answered Nov 04 '25 13:11

8176135