rust - 为什么 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 `()`
但如果你添加“;” 在假之后,一切仍然有效。
解决方案
您缺少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
}
}
推荐阅读
- javascript - 通过几个键/值对查找对象是否是数组的成员
- android - Why can I not instantiate AccountManager?
- vba - 延迟通过 EWS 发送电子邮件会将邮件留在已发送项目中,而不会实际发送
- node.js - Installing node package globally without internet on server error: No such file or directory
- python - 如何在 kivy 和 kivymd 中访问具有 id 的元素
- sql - 如何在oracle sql中使用case条件组合列
- c++ - 文本文件中出现的字母
- mixins - 当原始变量具有默认强制时,有没有办法访问混合组件?
- xml - 使用 UTF-16LE 编码在 PySpark 中读取 XML 文件
- javascript - 如何使用 Twilio 可编程视频在远程参与者上全屏显示屏幕共享视频?