首页 > 解决方案 > 为什么 rust 在应该 bool 时会期望 ()?

问题描述

我的 rust 代码应该返回一个布尔值,但由于某种原因, () 是预期的。这是怎么回事?

fn create_file(path: &Path) -> bool {
    // if file already exist
    if path.is_file(){
        false
    }
    let mut file = File::create(path);
    true
}

错误:

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 `()`

但如果你添加“;” 在假之后,一切仍然有效。

标签: rust

解决方案


您缺少returnelse。使用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
    }
}

推荐阅读