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

代码如下:

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的,但是却报错了.

阅读 7.1k
1 个回答

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

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进