学习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的,但是却报错了.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不是File::create()返回值的问题, 是你的main()函数的返回值的问题, 应该写成
fn main() -> std::io::Result<()>
.官方文档的示例中有写, 可以参考一下.