Use the memmap2 crate to map files directly into memory for fast, array-like access in Rust.
Use the memmap2 crate to map files into memory for efficient access without manual I/O calls.
use memmap2::MmapOptions;
use std::fs::File;
fn main() {
let file = File::open("data.bin").unwrap();
let mmap = unsafe { MmapOptions::new().map(&file).unwrap() };
println!("First byte: {}", mmap[0]);
}
Add memmap2 = "0.9" to your Cargo.toml dependencies.
Memory mapping lets your program treat a file on disk like a regular array in memory. This avoids the slow process of reading data in chunks and lets the operating system handle loading only what you need. Think of it like opening a book and reading any page instantly without having to flip through every previous page first.