相关疑难解决方法(0)

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

我正在阅读以下文档File:

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

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

rust

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

我应该避免在生产应用程序中打开包装吗?

在运行时很容易崩溃unwrap:

fn main() {
    c().unwrap();
}

fn c() -> Option<i64> {
    None
}
Run Code Online (Sandbox Code Playgroud)

结果:

   Compiling playground v0.0.1 (file:///playground)
 Running `target/debug/playground`
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', ../src/libcore/option.rs:325
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: Process didn't exit successfully: `target/debug/playground` (exit code: 101)
Run Code Online (Sandbox Code Playgroud)

unwrap唯一专为快速测试和证明的概念?

我不能肯定"我的程序不会崩溃,所以我可以使用unwrap",如果我真的想panic!在运行时避免,我认为避免panic!是我们想要的生产应用程序.

换句话说,如果我使用,我可以说我的程序是可靠的unwrap吗?或者unwrap即使案件看似简单,我也必须避免吗?

我读到了这个答案:

当您确定没有错误时,最好使用它.

但我认为我不能"肯定".

我不认为这是一个意见问题,而是一个关于Rust核心和编程的问题.

error-handling rust

16
推荐指数
3
解决办法
1555
查看次数

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
查看次数

从匹配到Err(e)的返回值

我正在尝试在Rust中编写一个简单的TCP echo服务器,我对如何将匹配的值返回到Err感到困惑.

我知道返回类型应该是usize,并且我想返回零.在其他语言中,我只是,return 0;但Rust不会让我.我也试过了usize::Zero().我确实通过这样let s:usize = 0; s做得到它,但这看起来非常愚蠢,我想有更好的方法来做到这一点.

let buffer_length =  match stream.read(&mut buffer) {
    Err(e) => {
         println!("Error reading from socket stream: {}", e);
         // what do i return here?
         // right now i just panic!
         // return 0;
    },
    Ok(buffer_length) => {
        stream.write(&buffer).unwrap();
        buffer_length
    },
};
Run Code Online (Sandbox Code Playgroud)

我知道我也可能只是没有match返回任何内容并且buffer_lengthmatch函数调用之内消耗,但在这种情况下我不想这样做.

处理这样的事情最常用的方法是什么?

rust

8
推荐指数
1
解决办法
5145
查看次数

处理/解包嵌套Result类型的惯用方法是什么?

我读到使用unwrapon Result在Rust中不是一个好习惯,并且最好使用模式匹配,因此可以适当地处理发生的任何错误.

我明白了这一点,但考虑一下读取目录的片段并打印每个条目的访问时间:

use std::fs;
use std::path::Path;

fn main() {
    let path = Path::new(".");
    match fs::read_dir(&path) {
        Ok(entries) => {
            for entry in entries {
                match entry {
                    Ok(ent) => {
                        match ent.metadata() {
                            Ok(meta) => {
                                match meta.accessed() {
                                    Ok(time) => {
                                        println!("{:?}", time);
                                    },
                                    Err(_) => panic!("will be handled")
                                }
                            },
                            Err(_) => panic!("will be handled")
                        }
                    },
                    Err(_) => panic!("will be handled")
                }
            }
        },
        Err(_) => panic!("will be handled")
    }
}
Run Code Online (Sandbox Code Playgroud)

我想处理上面代码中的每个可能的错误(panic …

coding-style rust

6
推荐指数
1
解决办法
884
查看次数

来自fn的Rust返回结果错误

我希望此函数返回错误结果:

fn get_result() -> Result<String, std::io::Error> {
     // Ok(String::from("foo")) <- works fine
     Result::Err(String::from("foo"))
}
Run Code Online (Sandbox Code Playgroud)

错误信息

error[E0308]: mismatched types
 --> src/main.rs:3:17
  |
3 |     Result::Err(String::from("foo"))
  |                 ^^^^^^^^^^^^^^^^^^^ expected struct `std::io::Error`, found struct `std::string::String`
  |
  = note: expected type `std::io::Error`
             found type `std::string::String`
Run Code Online (Sandbox Code Playgroud)

我很困惑如何在使用预期的结构时打印出错误消息.

rust rust-result

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

标签 统计

rust ×6

coding-style ×1

error-handling ×1

rust-result ×1