Read and Write contracts
Quick answer
The Read and Write traits describe byte input and output independently of the underlying device. A file, socket or memory buffer can implement these traits. A single operation may transfer fewer bytes than requested.
Partial operations and exact transfers
read returns the number of bytes read; zero with a nonempty buffer usually indicates EOF on a stream. read_exact fills the buffer or returns an error. write reports bytes accepted; write_all tries to send all bytes or returns an error. Errors may occur after partial progress; neither exact operation is transactional.
use std::io::{self, Read};fn main() -> io::Result<()> { let mut input = &b"abc"[..]; let mut header = [0; 2]; input.read_exact(&mut header)?; println!("{}", std::str::from_utf8(&header).unwrap()); println!("remaining: {}", input.len()); Ok(()) }Expected stdout (not executed):
abremaining: 1Two bytes are consumed; one remains.
use std::io::{self, Write};fn main() -> io::Result<()> { let mut bytes = Vec::new(); bytes.write_all(b"hi")?; bytes.write_all(b"!")?; println!("{}", String::from_utf8(bytes).unwrap()); Ok(()) }Expected stdout (not executed):
hi!Vec<u8> implements Write, allowing a test without files.
Common mistake
Do not assume read fills its buffer or ignore the count returned by write.
Try it yourself
Try read_exact with a four-byte buffer and a three-byte input; inspect the error kind locally.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Read and Write contracts — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A writer reports accepting only two of six bytes. What is the correct next step?
Read and Write contracts — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{self, Read}; fn main() -> io::Result<()> { let mut input = &b"abc"[..]; let mut header = [0; 2]; input.read_exact(&mut header)?; println!("{}", std::str::from_utf8(&header).unwrap()); println!("remaining: {}", input.len()); Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Read and Write contracts — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{self, Write}; fn main() -> io::Result<()> { let mut bytes = Vec::new(); bytes.write_all(b"hi")?; bytes.write_all(b"!")?; println!("{}", String::from_utf8(bytes).unwrap()); Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.