A Read trait defines shared read-related behavior that several types can implement. The trait keyword declares the behavior; impl connects it to a concrete type. section 3.6.1
A minimal File reader
The example declares read(&self, &mut Vec<u8>) -> Result<usize, String>, implements it for File, and calls f.read(&mut buffer).unwrap(). Its placeholder implementation returns Ok(0), showing the interface before real input handling. section 3.6.1
Rust’s standard-library Read trait applies the same idea to real input. A byte slice can be read like a file, while read_exact transfers bytes into a supplied buffer until the buffer is full or an error occurs. section 7.3
A practical file viewer uses Read to:
- Open a filename supplied through the command line. section 7.3
- Read fixed-size sixteen-byte buffers with read_exact. section 7.3
- Print offsets and represent bytes as hexadecimal values or markers. section 7.3
Listing 3.12 Defining the bare bones of a Read trait for File
#![allow(unused_variables)] #1
#[derive(Debug)]
struct File; #2
trait Read { #3
fn read(
self: &Self,
save_to: &mut Vec<u8>,
) -> Result<usize, String>; #4
}
impl Read for File {
fn read(self: &File, save_to: &mut Vec<u8>) -> Result<usize, String> {
Ok(0) #5
}
}
fn main() {
let f = File{};
let mut buffer = vec!();
let n_bytes = f.read(&mut buffer).unwrap();
println!("{} byte(s) read from {:?}", n_bytes, f);
}
Inspect the complete minimal trait declaration, File implementation, buffer call, and printed result. section 3.6.1
