raw_os_error Reads The OS Error Code
Read the OS error number behind an io::Error with raw_os_error, and build one back with from_raw_os_error for a faithful round trip.
Code
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");
}Inside the snippet
Count the function main as the entire surface area of raw_os_error Reads The OS Error Code.
Watch out for
- Runs on the standard library alone; nothing to install.
Using it
The primary signature is fn main()
The run emits 4 labeled sections — kind:, os code:, custom error has no os code, roundtrip kind matches — one per step.
Key statements
assert_eq!(err.raw_os_error(), Some(2));
Interactive Tools for This Topic
FAQ
- What does raw_os_error Reads The OS Error Code print when run?
- Run it as a complete program — the output lines carry labels such as `kind:`, `os code:`, `custom error has no os code`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.