这个问题在这里已有答案:
use std::io;
use std::fs::File;
use std::io::prelude::*;
fn main() {
let mut csv = File::open("Item.csv")?;
}
这是我的代码的一部分,我有错误:
Compiling eracsv v0.1.0 (file:///C:/Users/jwm/Project/eracsv)
error[E0277]: the trait bound `(): std::ops::Try` is not satisfied
--> src\main.rs:
|
| let mut csv = File::open("Item.csv")?;
| -----------------------
| |
| the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
| in this macro invocation
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
我已经处理了rustc 1.19稳定和每晚1.22并且都出现了相同的错误 .
但是,这与rust doc完全相同,不是吗?明确提到File :: open()函数返回结果 .
我很好奇为什么?运算符使编译错误,而unwrap()没有 .
1 回答
错误消息实际告诉您的是您在函数内部使用
?
运算符返回()
(这是main
函数) .?
运算符向上传播错误,但只有在它实际使用的函数实际上具有可表示该错误的兼容返回类型时才能执行此操作 .或者换句话说,您只能在自身返回
Result
(具有兼容的错误类型)的函数中使用它 . 您的main
不会返回Result
,因此您无法在其中使用?
运算符 .您可能也对RFC 1937感兴趣,这将允许在
main
中使用?
(允许您声明main
返回Result
) .