gpt4 book ai didi

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

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

我的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/

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