gpt4 book ai didi

rust - 预期的单位类型 '()',找到了 'enum std::option::Option'

转载 作者:行者123 更新时间:2023-12-03 11:34:02 25 4
gpt4 key购买 nike

我有看起来像这样的功能:

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<_>`
我不确定自己在做什么错。任何帮助,将不胜感激

最佳答案

No ;返回值只能在块的末尾使用。
要解决此问题,您可以:

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.
}

关于rust - 预期的单位类型 '()',找到了 'enum std::option::Option',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63654523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com