代码如下:
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的,但是却报错了.
不是File::create()返回值的问题, 是你的main()函数的返回值的问题, 应该写成
fn main() -> std::io::Result<()>
.官方文档的示例中有写, 可以参考一下.