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

IO Traits

Traits สำหรับ input/output operations

use std::io::{Read, Cursor};
fn main() {
let data = b"Hello, World!";
let mut cursor = Cursor::new(data);
// read - fill buffer
let mut buf = [0u8; 5];
let n = cursor.read(&mut buf).unwrap();
println!("Read {} bytes: {:?}", n, String::from_utf8_lossy(&buf));
// read_exact - must fill exactly
cursor.set_position(0);
let mut buf = [0u8; 5];
cursor.read_exact(&mut buf).unwrap();
println!("Exact: {:?}", String::from_utf8_lossy(&buf));
// read_to_end - read all to Vec
cursor.set_position(0);
let mut vec = Vec::new();
cursor.read_to_end(&mut vec).unwrap();
println!("All bytes: {:?}", vec);
// read_to_string - read all as String
cursor.set_position(0);
let mut s = String::new();
cursor.read_to_string(&mut s).unwrap();
println!("String: {}", s);
// bytes() iterator
cursor.set_position(0);
println!("\nBytes:");
for byte in cursor.bytes().take(5) {
print!("{:02x} ", byte.unwrap());
}
println!();
}

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

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