rust - 为什么 rust 应该期望()何时沸腾?

标签 rust

我的rust代码应该返回一个 bool 值,但是由于某些原因,应该使用()。
怎么了

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 `()`
但是,如果您添加“;”错误之后,那么一切仍然有效。

最佳答案

您缺少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
    }
}

关于rust - 为什么 rust 应该期望()何时沸腾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63426862/

相关文章:

rust - 如何使用 Serde 在序列化期间转换字段?

rust - 特质有时可以 move

rust - 设置 GTK 应用程序标题

generics - “cannot borrow as mutable more than once”,即使是在放弃第一次借阅后

rust - Iterator::all 是如何工作的?

c++ - 如何将 Windows SOCKADDR_BTH 的 C++ 转换复制到 Rust 中的 SOCKADDR?

generics - 将 trait 中方法的返回类型与实现该 trait 的类型绑定(bind)

rust - 如何在match语句分支中声明变量?

rust - 有没有更优雅的方法来用默认字符串解开 Option<Cookie> ?

rust - 我如何根据其中一个 Vec 中的值对两个 Vec 进行共同排序?