error-handling - 有没有办法从std::io::Error获取OS错误代码?

标签 error-handling rust

当我运行以下命令时:

use std::fs::File;

fn main() {
    let filename = "not_exists.txt";
    let reader = File::open(filename);

    match reader {
        Ok(_) => println!(" * file '{}' opened successfully.", filename),
        Err(e) => {
            println!("{:?}", &e);
        }
    }
}
输出为:
Os { code: 2, kind: NotFound, message: "No such file or directory" }
是否可以将该代码作为整数获取?

最佳答案

使用 io::Error::raw_os_error :

match reader {
    Ok(_) => println!(" * file '{}' opened successfully.", filename),
    Err(e) => println!("{:?}", e.raw_os_error()),
}
输出:
Some(2)
也可以看看:
  • How does one get the error message as provided by the system without the "os error n" suffix?
  • 关于error-handling - 有没有办法从std::io::Error获取OS错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66212606/

    相关文章:

    rust - 为什么复制 C 对无符号整数的 fread 的通用函数总是返回零?

    memory - 如何将拥有的盒子发送给子任务?

    service - 如何在Windows Service应用程序中向用户创建提示/通知?

    jquery - 处理跨域 jsonp 调用的 jQuery.ajax 错误

    c# - 是否可以在空检查中推断类型的名称

    c# - 以编程方式(C#)检测队列不再能够接收消息的最佳方法是什么?

    linux - BASH 脚本中的错误退出不起作用

    rust - 如何将 &mut T 类型转换为 &mut U 类型?

    segmentation-fault - 为什么这个 Rust 程序不会崩溃?

    rust - 我怎样才能将两个 futures 链接到同一个资源上,而不必提前定义每个方法组合?