繁体   English   中英

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

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

我有 function 看起来像这样:

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

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

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<_>`

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

没有; 返回只能在块的末尾使用。

要解决此问题,您可以:

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

要么

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM