error-concept

Partial reads: loop until EOF

With a nonempty buffer, handle successful short reads, EOF and errors separately. Retry Interrupted, but return or explicitly handle other errors rather than busy-looping. This example consumes a finite source in small chunks. Expected stdout (not executed): 6 Common mistake: Breaking on any short read instead of handling its valid bytes.

Formal Syntax & Structure

rust syntaxrust
match reader.read(&mut buffer) { Ok(0) => ..., Ok(n) => ..., Err(e) => ... }

Working Example

Example Snippetrust
fn main() {    use std::io::{Read, ErrorKind};    let mut source = &b"abcdef"[..];    let mut buf = [0; 2];    let mut total = 0;    loop { match source.read(&mut buf) {        Ok(0) => break,        Ok(n) => total += n,        Err(e) if e.kind() == ErrorKind::Interrupted => continue,        Err(e) => panic!("read failed: {e}"),    } }    println!("{total}");}
Rust Reference