我正在阅读以下文档File:
//..
let mut file = File::create("foo.txt")?;
//..
Run Code Online (Sandbox Code Playgroud)
什么是?在这条线?我不记得以前在Rust Book中看过它了.
我想学习如何正确处理Rust中的错误.我读过这本书和这个例子 ; 现在我想知道我应该如何处理这个函数中的错误:
fn get_synch_point(&self) -> Result<pv::synch::MeasPeriods, reqwest::Error> {
let url = self.root.join("/term/pv/synch"); // self.root is url::Url
let url = match url {
Ok(url) => url,
// ** this err here is url::ParseError and can be converted to Error::Kind https://docs.rs/reqwest/0.8.3/src/reqwest/error.rs.html#54-57 **//
Err(err) => {
return Err(Error {
kind: ::std::convert::From::from(err),
url: url.ok(),
})
}
};
Ok(reqwest::get(url)?.json()?) //this return reqwest::Error or convert to pv::sych::MeasPeriods automaticly
}
Run Code Online (Sandbox Code Playgroud)
这段代码不合适; 它会导致编译错误:
error[E0451]: field `kind` of struct `reqwest::Error` is private
--> src/main.rs:34:42
| …Run Code Online (Sandbox Code Playgroud) 如果条件为真,我想从函数返回错误:
use std::error::Error;
pub fn run() -> Result<(), Box<Error>> {
// -- snip ---
if condition {
// return error
}
// -- snip --
Ok(())
}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
我可能没有类型系统的基础知识,但是在我所看到的所有地方,人们都在使用?运算符,所以我无法弄清楚要返回哪种类型。