相关疑难解决方法(0)

这个问号操作员是关于什么的?

我正在阅读以下文档File:

//..
let mut file = File::create("foo.txt")?;
//..
Run Code Online (Sandbox Code Playgroud)

什么是?在这条线?我不记得以前在Rust Book中看过它了.

rust

58
推荐指数
3
解决办法
2万
查看次数

Rust正确的错误处理(从一种错误类型自动转换为带问号的另一种错误类型)

我想学习如何正确处理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)

rust

15
推荐指数
3
解决办法
4814
查看次数

如何手动返回Result &lt;(),Box &lt;Error &gt;&gt;?

如果条件为真,我想从函数返回错误:

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)

我可能没有类型系统的基础知识,但是在我所看到的所有地方,人们都在使用?运算符,所以我无法弄清楚要返回哪种类型。

  1. 是否可以仅返回这样的错误?
  2. 有没有更好的方法来处理这种逻辑?

error-handling type-systems rust

5
推荐指数
3
解决办法
3491
查看次数

标签 统计

rust ×3

error-handling ×1

type-systems ×1