我的函数看起来像这样:
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)
我不确定我做错了什么。任何帮助,将不胜感激
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)
| 归档时间: |
|
| 查看次数: |
9204 次 |
| 最近记录: |