Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
Deep dive: atomic operations, memory orderings, and CAS loops — tools without locks but with sharper contracts. When atomics shine and when the mutex stays.
Where does data come from? From files, the network, the keyboard, or simply
from a byte array in memory. And where does it go? Into files, the network,
the console, or into a Vec<u8>.
Rust solves this with two traits that unify every source and destination:
std::io::Read.std::io::Write.use std::io::Read;
fn main() {
// A reader from an in-memory byte array
let mut reader = std::io::Cursor::new(b"hello, world".to_vec());
let mut buf = String::new();
reader.read_to_string(&mut buf).unwrap();
println!("{buf}"); // hello, world
}
File::open(filename) — read an existing fileTcpStream — receive data over the networkstdin() — the process's standard inputCursor<&[u8]>, Cursor<Vec<u8>> — "read" from an in-memory byte arrayFile::create(filename) — write a new fileTcpStream — send data over the networkstdout(), stderr() — write to the screenVec<u8> — write appends to the endCursor<Vec<u8>> — read and write with free positioningOne Trait, Many Sources
The magic: a function that takes a generic Read or Write implementation
works identically for files, network sockets, and buffers.
use std::io::{self, Read};
// Works with any source that can deliver bytes:
fn print_contents(mut source: impl Read) -> io::Result<()> {
let mut text = String::new();
source.read_to_string(&mut text)?;
println!("{text}");
Ok(())
}
It runs for File, TcpStream, Cursor, Stdin — without changing a line.
Check: Which type IS a reader?
Answer: std::io::stdin()
stdin() is a reader (implements Read). stdout() and File::create are writers (Write). Vec<u8> is a writer, not a reader.
⚠ Common mistake:
read_to_stringrequires valid UTF-8 — binary files or broken encodings abort withInvalidData: stream did not contain valid UTF-8. If you only need the raw bytes, read withread_to_endinto a byte buffer instead.
Takeaways:
System calls are slow. Hundreds of individual read calls across the
operating-system boundary are costly. The solution: a buffer in memory.
A BufReader fetches data in large blocks (several KB) from the OS and
serves many small read operations from it — almost no system calls at all.
use std::io::BufRead;
fn main() {
// Read a file line by line
let file = std::fs::File::open("test.txt").unwrap();
let buffered = std::io::BufReader::new(file);
for line in buffered.lines() {
// `lines()` yields lines WITHOUT the trailing '\n'
let line = line.unwrap();
println!("Line: {line}");
}
}
// test.txt containing the lines "alpha" and "beta":
// → Line: alpha
// → Line: beta
reader.read_line(&mut line) — read one line into a Stringreader.lines() — iterator over lines (newline stripped)reader.read_until(byte, &mut vec) — read up to a separator bytereader.split(byte) — iterator that splits on a bytelines() is almost always right
For text input, lines() is usually exactly what you want: it strips \n
(or \r\n on Windows) automatically. Here's a grep clone in Rust:
use std::io::{self, BufRead};
fn grep(target: &str) -> io::Result<()> {
for line_result in io::stdin().lock().lines() {
let line = line_result?;
if line.contains(target) {
println!("{line}");
}
}
Ok(())
}
stdin().lock() gives you a BufRead over standard input.
Check: What does reader.lines() strip from the yielded strings?
Answer: The line ending ('
' or '\r
')lines() yields each string without its line ending. For Windows endings (CR plus LF) both characters are stripped.
⚠ Common mistake:
read_line(&mut line)appends the text it read to the String instead of replacing it — skipline.clear()inside a loop and every line comes back with all previous lines glued on. Either clear before each call or use thelines()iterator, which yields fresh Strings.
Takeaways:
So far you've used println!(). For arbitrary writers there are write!()
and writeln!(). Two differences from println!:
Result — errors must be handled.use std::fs::File;
use std::io::{self, Write};
fn main() -> io::Result<()> {
let mut file = File::create("output.txt")?;
writeln!(file, "Line 1")?;
writeln!(file, "Line 2")?;
// Write to the standard error stream:
writeln!(io::stderr(), "Error: world not helloable")?;
Ok(())
}
File::open(filename) — opens an existing file for reading.File::create(filename) — creates a file for writing
(truncates it if it exists).When neither case fits, use OpenOptions:
use std::fs::OpenOptions;
fn log_entry(msg: &str) -> std::io::Result<()> {
// Append mode: do NOT truncate the existing file
let mut log = OpenOptions::new()
.append(true)
.open("server.log")?;
writeln!(log, "{msg}")
}
Who owns the File?
File::create returns an owned file. writeln!(file, ...) only borrows it.
You don't need to close it explicitly: when the File falls out of scope it is
closed automatically and any remaining data is written (flushed). In long-running
programs an explicit file.flush() is worthwhile so buffered data isn't forgotten.
Check: What does File::create do if a file with that name already exists?
Answer: It truncates (empties) it
File::create makes a new file. If it already exists, its contents are overwritten. To append you need OpenOptions with .append(true).
⚠ Common mistake: Without
use std::io::Write;the compiler aborts atwriteln!(file, ...)with E0599 — "no method namedwrite_fmtfound" — and the hint "traitWritewhich provideswrite_fmtis implemented but not in scope" gives away the fix. The trait must be in scope even thoughwriteln!looks like an import-free macro.
Takeaways:
Your operating system does not force filenames to be valid Unicode. On Linux
almost any byte sequence is an acceptable name — even \xf4.txt. But Rust
strings are always valid Unicode.
That's why std::ffi::OsStr and OsString exist: string types that can
represent anything the OS accepts as a name. And std::path::Path (with
PathBuf as the owning type) is a convenient view of OsStr with many
path methods.
| borrowed | owning | purpose |
|---|---|---|
str | String | Unicode text |
OsStr | OsString | anything the OS allows |
Path | PathBuf | filenames & paths, with methods |
use std::path::Path;
fn main() {
let base = Path::new("/home/user");
let full = base.join("project").join("Cargo.toml");
println!("{}", full.display());
// /home/user/project/Cargo.toml
println!("File name: {:?}", full.file_name());
println!("Extension: {:?}", full.extension());
println!("Parent: {:?}", full.parent());
println!("Does the file exist? {}", full.exists());
}
// → File name: Some("Cargo.toml")
// → Extension: Some("toml")
// → Parent: Some("/home/user/project")
.display() makes the path usable in println! — because Path itself
implements no Display, only Debug.
When Path, when OsStr?
Use Path/PathBuf for whole (relative or absolute) paths. For a
single component of a path (like a folder name), use OsStr. The
practical Rust idiom: never build paths by string concatenation — use join(),
which handles separators correctly on all platforms.
Check: Why does OsStr exist in addition to String?
Answer: It can represent non-Unicode filenames
OS filenames need not be valid Unicode. OsStr can represent any byte sequence the OS accepts, which String cannot.
⚠ Common mistake:
println!("{}", path)doesn't compile —Pathdoesn't implementDisplay, so the compiler reports E0277. Usepath.display()for console output, or the{:?}formatter for debugging.
Takeaways:
std::fs::read_dir returns an iterator over the entries of a folder. Each
entry is a DirEntry with methods such as path(), metadata(), and
file_type().
use std::fs;
fn main() -> std::io::Result<()> {
for entry in fs::read_dir(".")? {
let entry = entry?;
let kind = if entry.file_type()?.is_dir() {
"directory" } else { "file" };
println!("{kind:9} {}", entry.path().display());
}
Ok(())
}
fs::read_to_string(path) — read a whole file into a Stringfs::read(path) — read a whole file into a Vec<u8>fs::write(path, contents) — write a whole filefs::create_dir(path) / fs::create_dir_all(path) — create foldersfs::remove_file(path) / fs::remove_dir(path) — deletefs::copy(source, dest) — copyfs::rename(old, new) — move/renamefs::metadata(path) — size, timestamps, file typeread_to_string is handy for small files
To load a small config file entirely, read_to_string is ideal — no manual
reader and buffering needed:
fn load_points() -> std::io::Result<i32> {
let contents = std::fs::read_to_string("points.txt")?;
Ok(contents.trim().parse().unwrap_or(0))
}
For large files (movies, logs, downloads) use a reader or stream instead — don't swallow everything into memory at once.
Check: What does fs::read_to_string(path) return?
Answer: The entire file contents as a String
read_to_string reads the whole file into a String. For line-by-line reading, use a file plus BufReader/lines().
⚠ Common mistake:
read_dirhands you results nested twice: oneResultfor the call itself, then anotherResultper entry. Forget the second?inside the loop and you trip over "expectedDirEntry, foundResult" — each entry needs its own unwrap.
Takeaways:
For low-level networking, std::net provides blocking TCP and UDP I/O.
Two central types:
TcpListener — listens for incoming connections (server)TcpStream — an open connection (client AND server side)An echo server simply sends back everything it receives. With one thread per connection, you need only a few lines:
use std::net::{TcpListener, TcpStream};
use std::{io, thread};
fn handle_conn(mut stream: TcpStream) -> io::Result<()> {
// Echo: copy everything from stream back to itself.
let mut write_stream = stream.try_clone()?;
io::copy(&mut stream, &mut write_stream)?;
Ok(())
}
fn echo_main(addr: &str) -> io::Result<()> {
let listener = TcpListener::bind(addr)?;
println!("listening on {addr}");
for stream_result in listener.incoming() {
let stream = stream_result?;
let peer = stream.peer_addr()?;
println!("connection received from {peer}");
thread::spawn(move || {
if let Err(e) = handle_conn(stream) {
eprintln!("error in client thread: {e}");
}
});
}
Ok(())
}
fn main() {
echo_main("127.0.0.1:17007").expect("error: ");
}
// → listening on 127.0.0.1:17007
// → connection received from 127.0.0.1:52431
listener.incoming() — waits for connections, yields Result<TcpStream>stream.try_clone() — a second handle for writing (Rust needs &mut for copies)io::copy(reader, writer) — copies everything from reader to writerNetworking: I/O is the same everywhere
A TcpStream is simultaneously a Read and a Write. That's why the
reader/writer logic from the earlier lessons works on the network too — and
io::copy only needs an impl Read and an impl Write, whether it's a file
or a socket.
For high-performance servers handling thousands of connections you need asynchronous I/O (see Module 17) instead of a thread per connection.
Check: What does the TcpListener do in a server?
Answer: It listens for incoming connections
The TcpListener binds an address and accepts incoming connections (incoming()). TcpStream is then the individual connection.
⚠ Common mistake:
io::copy(&mut stream, &mut stream)borrows the same stream as mutable twice at once — E0499 ("cannot borrowstreamas mutable more than once at a time"). Onlystream.try_clone()gives you the second handle that lets reader and writer run side by side.
Takeaways:
Now you combine everything from this module into a real little tool:
BufReader + lines()).ERROR or PANIC.File::create + writeln!).stdout).This structure exercises: Reader/Writer traits, buffering, file paths, and
error handling with ? — exactly the repertoire applied from lessons 1–6.
Recipes from this module
BufReader::new(File::open(&path)?).lines()writeln!(File::create(&dest)?, "{line}")?println!("{line}")? upwardpath.display() for println!Scenario: The gigabyte log
⚠ Common mistake: Calling
File::createinside the loop truncates the output file on every pass — when the dust settles, only the last matching line survives. Open the file once before the loop and hold the handle across the iteration.
Takeaways:
Course navigation: ← Module 17 · All 27 modules · Module 19 →