Skip to content
เข้าสู่ระบบ

IO Enums

Enums สำหรับ I/O operations ใน Rust รวมถึง ErrorKind และ SeekFrom ที่ใช้กันบ่อย

ErrorKind enum จำแนกประเภทของ I/O errors ช่วยให้ handle errors แบบ portable ได้

use std::io::{self, ErrorKind};
use std::fs::File;
fn handle_error(err: io::Error) {
match err.kind() {
ErrorKind::NotFound => println!("File not found"),
ErrorKind::PermissionDenied => println!("Permission denied"),
ErrorKind::AlreadyExists => println!("Already exists"),
ErrorKind::ConnectionRefused => println!("Connection refused"),
ErrorKind::ConnectionReset => println!("Connection reset"),
ErrorKind::NotConnected => println!("Not connected"),
ErrorKind::AddrInUse => println!("Address in use"),
ErrorKind::BrokenPipe => println!("Broken pipe"),
ErrorKind::WouldBlock => println!("Would block"),
ErrorKind::InvalidInput => println!("Invalid input"),
ErrorKind::InvalidData => println!("Invalid data"),
ErrorKind::TimedOut => println!("Timed out"),
ErrorKind::WriteZero => println!("Write zero"),
ErrorKind::Interrupted => println!("Interrupted"),
ErrorKind::UnexpectedEof => println!("Unexpected EOF"),
_ => println!("Other error: {}", err),
}
}
fn main() {
// ============================================
// Create error from kind
// ============================================
let err = io::Error::from(ErrorKind::NotFound);
handle_error(err);
// ============================================
// Try opening non-existent file
// ============================================
match File::open("nonexistent.txt") {
Ok(_) => println!("Opened"),
Err(e) => handle_error(e),
}
// ============================================
// Custom error with message
// ============================================
let custom = io::Error::new(
ErrorKind::InvalidInput,
"Custom error message"
);
println!("Custom: {}", custom);
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด