预期的单位类型“()”,找到“enum std::option::Option”

Ach*_*113 4 rust

我的函数看起来像这样:

pub fn new(s: String) -> Option<i32> {
    if s.len() > 10 {
        None
    }
    Some(10)
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,我收到以下错误消息:

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<_>`
Run Code Online (Sandbox Code Playgroud)

我不确定我做错了什么。任何帮助,将不胜感激

Pri*_*six 8

No ;Returns 只能用在块的末尾。

要解决此问题,您可以:

pub fn new(s: String) -> Option<i32> {
    if s.len() > 10 {
        return None; // Add a early return here
    }
    Some(10)
}
Run Code Online (Sandbox Code Playgroud)

或者

pub fn new(s: String) -> Option<i32> {
    if s.len() > 10 {
        None
    } else {
        Some(10)
    } // This is now the end of the function block.
}
Run Code Online (Sandbox Code Playgroud)