我的 rust 代码应该返回一个布尔值,但由于某种原因, () 是预期的。这是怎么回事?
fn create_file(path: &Path) -> bool {
// if file already exist
if path.is_file(){
false
}
let mut file = File::create(path);
true
}
Run Code Online (Sandbox Code Playgroud)
错误:
error[E0308]: mismatched types
--> src/main.rs:53:9
|
52 | / if path.is_file(){
53 | | false
| | ^^^^^ expected `()`, found `bool`
54 | | }
| | -- help: consider using a semicolon here
| |_____|
| expected this to be `()`
Run Code Online (Sandbox Code Playgroud)
但是如果你加上“;” 在 false 之后,一切仍然有效。
您缺少return或else。使用else将使 if/else 块成为返回表达式
fn create_file(path: &Path) -> bool {
// if file already exist
if path.is_file(){
false
} else {
let mut file = File::create(path);
true
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |