On this page
  1. Read
  2. Signature & Overview
  3. Notes & Pitfalls
  4. Example

Read

Prev: `PathBuf` | Up: io_and_fs | Next: error_and_fmt
Rel: io_and_fs, rust/builtins
Ref: Rust std — Read
Tags: #public #prog #rust #stdlib #io_and_fs #tier/core


Signature & Overview

trait Read { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>; }  /* + Write */

Fundamental byte-stream traits implemented by File, TcpStream, Stdin, and &[u8].

Notes & Pitfalls

Example

use std::io::Read;

fn read_u16_be(mut src: impl Read) -> std::io::Result<u16> {
    let mut buf = [0u8; 2];
    src.read_exact(&mut buf)?;
    Ok(u16::from_be_bytes(buf))
}

fn main() {
    let raw: &[u8] = &[0x01, 0x00];
    assert_eq!(read_u16_be(raw).unwrap(), 256);
}

Linked from

Related notes