学习rust中fs模块,遇到can't use the ? operator

发布于 2022-09-11 21:49:31 字数 1376 浏览 19 评论 0

代码如下:

use std::fs::File;
use std::io::prelude::*;

fn main() {
    let mut file = File::create("test_fs.txt")?;
    file.write_all(b"Hello world!")?;
}

这是标准库文档中的示例,会出现以下错误:

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
 --> src/main.rs:5:20
  |
5 |     let mut file = File::create("test_fs.txt")?;
  |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
  |
  = help: the trait `std::ops::Try` is not implemented for `()`
  = note: required by `std::ops::Try::from_error`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
 --> src/main.rs:6:5
  |
6 |     file.write_all(b"Hello world!")?;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
  |
  = help: the trait `std::ops::Try` is not implemented for `()`
  = note: required by `std::ops::Try::from_error`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `fs_lib`.

提示说只能用于返回Result, Option的函数,但这里File::create函数的返回值就是Result的,但是却报错了.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何以心动 2022-09-18 21:49:31

不是File::create()返回值的问题, 是你的main()函数的返回值的问题, 应该写成fn main() -> std::io::Result<()>.

官方文档的示例中有写, 可以参考一下.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文