On this page
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
.read()may return fewer bytes than requested: Use.read_exact()for fixed-size headers or.read_to_end()/.read_to_string()for full streams.- Implemented for
&[u8],File,TcpStream, andBufReader: Makes I/O functions easy to unit-test with in-memory byte slices.
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
- tuts/rust/std/io_and_fs/PathBuf Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/io_and_fs Linked here; links to this page; shared tags: #prog, #rust, #stdlib
- tuts/rust/std/error_and_fmt Linked here; shared tags: #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/VecDeque shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Display shared tags: #prog, #rust, #stdlib, #tier