← 中文资源

简体中文版本

raw_os_error 读取 OS 错误码

raw_os_error 读出 io::Error 背后的 OS 错误码,from_raw_os_error 反向构造:错误码跨平台含义不同但可往返,自定义错误则返回 None。

阅读英文原文

实现说明

raw_os_error 读取 OS 错误码以函数 main为骨架。

使用要点

  • 直接运行文件,输出会带上标签,比如 kind:、os code:、custom error has no os code——输出的每一行都能指回产生它的那次调用。

常见问题

运行「raw_os_error 读取 OS 错误码」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 kind:、os code:、custom error has no os code 标签标明各步骤。

核心语句

assert_eq!(err.raw_os_error(), Some(2));

代码示例

use std::io::{Error, ErrorKind};

fn main() {
    // from_raw_os_error:用 OS 错误码构造 io::Error
    let err = Error::from_raw_os_error(2);
    println!("kind: {:?}", err.kind());
    println!("os code: {:?}", err.raw_os_error());
    assert_eq!(err.raw_os_error(), Some(2));

    // 错误码是 OS 相关的:unix 的 ENOENT 与 windows 的 FILE_NOT_FOUND 都映射到 NotFound
    assert_eq!(err.kind(), ErrorKind::NotFound);

    // 自定义消息不携带 OS 码:raw_os_error 返回 None
    let plain = Error::other("disk busy");
    assert!(plain.raw_os_error().is_none());
    println!("custom error has no os code");

    // 往返:同一错误码构造出的错误类型一致
    let again = Error::from_raw_os_error(2);
    assert_eq!(err.kind(), again.kind());
    println!("roundtrip kind matches");
}