Quick Start: Install Rust with rustup and learn the ownership, error handling, trait, and iterator patterns behind daily Rust work. Then build a tested command-line log analyzer in about 35 minutes. To run and edit the examples without installing Rust first, jump to the Practice Rust section in your browser.

Most developers hit the same wall in their first week with Rust. You write a working function in five minutes, hit borrow of moved value, and scatter .clone() and .unwrap() across the file until the compiler goes quiet. The program compiles, runs slower than it should, and panics on the first malformed input.

Learning a small set of idiomatic moves removes that fight. Design around ownership, slices, Result, traits, and iterators from the start, and the compiler catches memory bugs, missing cases, and data races before your code ever runs.

What You’ll Learn

  • What is Rust, and what problem does it solve?
  • When should you choose Rust, and when is another language a better fit?
  • How do ownership, borrowing, and Resource Acquisition Is Initialization (RAII) manage memory without a garbage collector?
  • How do Option, Result, custom error enums, and ? replace null pointers and exceptions?
  • How do traits, generics, iterators, and newtypes structure idiomatic Rust code?
  • Which five common traps slow down new Rust developers, and how do you avoid them?
  • How do you build and test a working command-line log analyzer with Cargo?
  • Where can you go to learn more about Rust?

The Basics

Rust is a compiled systems programming language that checks memory safety and thread safety at compile time, without a garbage collector. Graydon Hoare started Rust in 2006, Mozilla adopted it in 2009, and Rust 1.0 shipped in 2015. The Rust 2024 Edition stabilized in Rust 1.85.0 in February 2025.

The motivation is practical security and reliability. As a historical baseline, a 2019 Microsoft Security Response Center analysis traced about 70% of Microsoft security vulnerabilities to C and C++ memory safety bugs. Those bugs include out-of-bounds reads, null dereferences, use-after-free errors, and double frees.

Moving new code to memory-safe languages shifts that ratio. In November 2025, Google reported in Rust in Android that Android memory safety vulnerabilities dropped below 20% of total vulnerabilities for the first time. Safe Rust enforces ownership and borrowing at compile time to rule out those bugs and data races. For the conceptual model behind why Rust works this way, read Fundamentals of Rust.

This guide teaches the 20% of Rust behind 80% of daily work, grounded in Brenden Matthews’ Idiomatic Rust. Focus on Cargo, ownership and RAII, borrowing and slices, Option and Result with ?, pattern matching, traits, iterators, newtypes, and five common traps. In Scaling Rust Adoption Through Training, Google explained that it designed its four-day Comprehensive Rust course to give engineers a solid foundation in days rather than weeks. Leave macros, unsafe, async runtimes, and manual lifetime annotations for the resources at the end.

Primary Use Cases

  • Command-line interface (CLI) tools and developer utilities that ship as fast single binaries.
  • Network services, proxies, and cloud microservices, including Amazon Web Services Lambda functions where fast cold starts and low memory lower cost.
  • Systems software, embedded firmware, operating system components, and storage engines.
  • WebAssembly modules and native extensions for Python, JavaScript, or Ruby.
  • Security-sensitive parsers and infrastructure platforms where predictable latency and memory safety matter.

Less Suitable Use Cases

  • Throwaway scripts and quick glue code, where Python or shell scripts finish faster.
  • Rapid product prototypes whose requirements change every few hours, where strict type design slows early exploration.
  • Graphical desktop and mobile apps when you need mature widget ecosystems today. Rust frameworks such as Dioxus are active and growing, yet younger than established web and native toolkits.

When to Use Rust

Pick Rust when correctness, predictable performance, and low memory usage matter over the life of the software. In Idiomatic Rust, Matthews compares choosing Rust to buying an insurance policy. You pay upfront in design discipline and compiler checks to avoid whole classes of memory crashes and security incidents later. When iteration speed matters more than runtime efficiency or strict safety guarantees, reach for Python, TypeScript, or Go instead.

The 20% That Does 80%

Once Rust fits the problem, a small set of toolchain commands and ownership idioms covers most daily work. Every code example and output below runs on rustc 1.100.0 and cargo 1.100.0 (Rust 2024 edition; all examples also compile on Rust 1.85+ or Rust 2021).

Set up Rust and Cargo

You’ll need:

  • A terminal, a text editor, and a system C linker (Xcode Command Line Tools on macOS, build-essential on Debian/Ubuntu, or Visual Studio C++ Build Tools on Windows).
  • Experience in at least one other programming language (such as Python, JavaScript, Go, Java, or C++).
  • About 35 minutes (roughly 20 minutes for the core patterns and 15 minutes for the build).

Install rustup, the official Rust toolchain manager, on macOS or Linux (on Windows, download rustup-init.exe from rustup.rs). To inspect the script before running it, download it with curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs -o rustup-init.sh, read the file, and run sh rustup-init.sh. Otherwise run the installer directly. It writes to ~/.cargo and ~/.rustup, updates your shell profile, and prompts for options; press Enter to accept the default toolchain:

Runs on your machine, not in the practice shell

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Open a new terminal (or run source "$HOME/.cargo/env") and check that the compiler and Cargo, Rust’s build system and package manager, are available:

Runs on your machine, not in the practice shell

rustc --version
cargo --version
rustc 1.100.0 (0ef1bc386 2026-11-09)
cargo 1.100.0 (3acc79c0c 2026-11-05)

Your version number and commit hash may differ; any Rust 1.85 or newer release supports the Rust 2024 edition used below.

Six Cargo commands handle almost every daily task:

cargo new <name>

Create a new binary project with Cargo.toml and src/main.rs. Add --lib for a library crate.

cargo check

Type-check and borrow-check the project without generating a binary. Use this for the fastest feedback loop.

cargo run / cargo test

Compile and run your binary, or compile and run every #[test] function and doc test in the crate.

cargo fmt / cargo clippy

Format code to community standards and catch non-idiomatic patterns, naming mistakes, and needless clones automatically.

Run cargo fmt and cargo clippy from day one. The compiler warns on non-standard naming (snake_case for functions and variables, UpperCamelCase for types, and SCREAMING_SNAKE_CASE for constants). Clippy flags non-idiomatic patterns and needless clones while you learn.

To run the five standalone examples below, try them directly in the Practice Rust section on this page or paste each one into the official Rust Playground. To run them locally, create a scratch crate with cargo new scratch, move into it (cd scratch), replace src/main.rs, and run cargo run.

Own your data and let RAII clean it up

Variables in Rust are immutable by default. Write let when a binding stays fixed, and opt in to mutation with let mut.

Every value has one owner at a time. Assigning a heap-allocated type such as String or Vec<T> to a new binding moves ownership instead of copying memory. Primitive stack values such as i32, f64, and bool implement Copy and duplicate cheaply.

When an owner leaves its scope, Rust runs its Drop destructor automatically. This Resource Acquisition Is Initialization (RAII) pattern frees heap memory, closes open File handles, and releases Mutex locks deterministically without a garbage collector.

fn print_length(text: &str) {
    println!("{text} has {} bytes", text.len());
}

fn main() {
    let message = String::from("hello rust");
    print_length(&message); // borrow without moving
    let moved = message;    // ownership transfers to `moved`
    println!("{moved}");
    // `moved` drops here and frees its heap memory automatically
}

What you get:

hello rust has 10 bytes
hello rust

Try printing message after let moved = message; and the compiler stops with error[E0382]: borrow of moved value. That check is why Rust prevents use-after-free and double-free bugs at compile time. Moving every value into every helper quickly gets tedious, which is where borrowing comes in.

Borrow by default, and prefer slices over owned collections

Borrowing lets a function read or update data without taking ownership. The borrow checker enforces three constraints at compile time:

Shared reads (&T)

Hold any number of immutable references to the same value at once. No reader can change the data underneath another.

Exclusive write (&mut T)

Hold at most one mutable reference to a value at a time, with zero immutable references active at the same moment.

Valid lifetimes

Every reference must stay shorter-lived than the owner it points to, preventing dangling pointers without runtime checks.

When designing a function signature, decide how to accept each parameter before writing the body:

flowchart TB A["Need to pass a value to a function"] --> B{"Is it a small Copy primitive
(i32, bool, u64)?"} B -->|Yes| C["Pass by value (T)"] B -->|No| D{"Must the function take ownership
or consume the value?"} D -->|Yes| E["Pass by value (T or mut T)"] D -->|No| F{"Must the function modify
the caller's value in place?"} F -->|Yes| G["Pass by mutable reference (&mut T)"] F -->|No| H["Pass by shared reference (&T,
preferring &str or &[T])"]

Follow two function-design habits from Idiomatic Rust: accept slices in function parameters and default to Vec<T> for collections. Accepting &str works with both string literals and &String; accepting &[T] works with arrays, slices, and &Vec<T>.

fn average(values: &[f64]) -> Option<f64> {
    if values.is_empty() {
        return None;
    }
    let sum: f64 = values.iter().sum();
    Some(sum / values.len() as f64)
}

fn main() {
    let readings = vec![12.0, 18.0, 24.0];
    let array = [10.0, 20.0];
    println!("vec avg: {:?}", average(&readings));
    println!("array avg: {:?}", average(&array));
    println!("empty avg: {:?}", average(&[]));
}

What you get:

vec avg: Some(18.0)
array avg: Some(15.0)
empty avg: None

Because Vec<T> stores elements in one contiguous block of memory, it stays cache-friendly and outperforms LinkedList on most workloads. Start with Vec<T>, HashMap, or BTreeMap from the standard library, and benchmark before reaching for custom containers. The average function above returned Option<f64> instead of throwing or returning a sentinel value; next, use Option, Result, and ? to handle absence and errors explicitly.

Replace null and exceptions with Option, Result, and ?

Rust has no null and no thrown exceptions. Absence is explicit through Option<T> (Some(value) or None), and recoverable failure is explicit through Result<T, E> (Ok(value) or Err(error)). Core types such as Option, Result, Vec, String, and From enter every module automatically through the Rust Standard Library Prelude. Exhaustive match expressions require you to handle every variant, so the compiler flags missed cases immediately.

When a function performs several fallible steps, define an error enum, implement Display, std::error::Error, and From, and propagate failures with ?. Postfixing ? unwraps Ok(value) or returns Err(error) early after converting the error with From.

use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum ConfigError {
    MissingValue,
    InvalidNumber(ParseIntError),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingValue => write!(f, "missing port value"),
            Self::InvalidNumber(err) => write!(f, "invalid port number: {err}"),
        }
    }
}

impl std::error::Error for ConfigError {}

impl From<ParseIntError> for ConfigError {
    fn from(err: ParseIntError) -> Self {
        Self::InvalidNumber(err)
    }
}

fn parse_port(line: &str) -> Result<u16, ConfigError> {
    let raw = line.split('=').nth(1).ok_or(ConfigError::MissingValue)?;
    let port: u16 = raw.trim().parse()?;
    Ok(port)
}

fn main() {
    for sample in ["port=8080", "port=abc", "port"] {
        match parse_port(sample) {
            Ok(port) => println!("{sample} -> ok ({port})"),
            Err(err) => println!("{sample} -> error ({err})"),
        }
    }
}

What you get:

port=8080 -> ok (8080)
port=abc -> error (invalid port number: invalid digit found in string)
port -> error (missing port value)

Convert between Option and Result with .ok_or(...), .ok(), and .map_err(...) instead of nesting match blocks. Implementing Display and From above already used traits; next, use traits, generics, and newtypes to organize your own types cleanly.

Share behavior with traits, generics, and newtypes

Rust skips class inheritance. Structs and enums hold state; traits define shared behavior that any type in your crate can implement. You also get common behavior with zero boilerplate via #[derive(Debug, Clone, PartialEq, Default)], and you construct types through conventional associated functions named new.

Combine traits with generics and where bounds to write reusable functions with static dispatch (zero runtime vtable cost). Use dynamic trait objects (Box<dyn Trait>) only when one collection must store mixed concrete types at runtime.

Wrap primitive values such as milliseconds, bytes, or IDs in single-field tuple structs called newtypes (struct LatencyMs(u64);). Newtypes prevent mixing incompatible units at compile time and carry zero runtime overhead. Follow the standard library’s conversion naming convention: as_* borrows cheaply, to_* computes or allocates, and into_* consumes self.

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct LatencyMs(u64);

impl LatencyMs {
    fn as_millis(&self) -> u64 {
        self.0
    }
}

trait Reportable {
    fn label(&self) -> String;
}

struct Endpoint {
    path: String,
    latency: LatencyMs,
}

impl Endpoint {
    fn new(path: &str, latency: LatencyMs) -> Self {
        Self {
            path: path.to_string(),
            latency,
        }
    }
}

impl Reportable for Endpoint {
    fn label(&self) -> String {
        format!("{} ({} ms)", self.path, self.latency.as_millis())
    }
}

fn print_report<T>(item: &T)
where
    T: Reportable,
{
    println!("{}", item.label());
}

fn main() {
    let health = Endpoint::new("/health", LatencyMs(12));
    print_report(&health);
}

What you get:

/health (12 ms)

Keep struct fields private by default and expose methods that return slices (&str, &[T]) instead of exposing internal Vec or String fields directly.

Transform collections with iterators and closures

Instead of writing index-based for loops with manual bounds, chain lazy iterators with closures (|arg| expr). Standard collections expose three ways to iterate:

  • .iter() borrows immutable references (&T), leaving the collection intact.
  • .iter_mut() borrows mutable references (&mut T) to update items in place.
  • .into_iter() consumes the collection and yields owned values (T).
fn main() {
    let latencies_ms = vec![14, 240, 38, 512, 95];

    let slow_total: u64 = latencies_ms
        .iter()
        .copied()
        .filter(|&ms| ms >= 100)
        .sum();

    let slow_count = latencies_ms
        .iter()
        .copied()
        .filter(|&ms| ms >= 100)
        .count();
    println!("slow requests: {slow_count}, total: {slow_total} ms");
}

What you get:

slow requests: 2, total: 752 ms

Iterators stay lazy until a consumer such as .sum(), .count(), .collect(), or a for loop drives them. The optimizer then compiles chained adapters into tight loops with no intermediate allocations. Both chains reuse latencies_ms because .iter() borrows the vector instead of consuming it; .into_iter() would move it on the first call.

Avoid the five common Rust traps

Chapter 10 of Idiomatic Rust catalogs the mistakes that most often derail new Rust codebases. Watch for these five habits during code review:

1. Lazy .unwrap() calls

Calling .unwrap() turns recoverable errors into crashes. Propagate with ?, handle with match, supply a default with unwrap_or, or document proven invariants with expect.

2. Panic-cloning .clone()

Cloning to silence the borrow checker hides design mistakes and wastes memory. Rethink who owns the data or pass a slice (&str, &[T]) first; clone only when you intentionally need an independent copy.

3. Skipping Vec<T>

Reaching for LinkedList or premature maps before measuring usually hurts speed and ergonomics. Start with Vec<T> for contiguous cache locality and benchmark before switching.

4. Deref inheritance

Implementing Deref on a struct to fake Java or C++ superclass inheritance confuses callers. Use traits or explicit accessor methods instead.

5. Premature smart pointers

Wrapping data in Rc<RefCell<T>> or Vec<Box<String>> adds heap allocations and moves borrow errors to runtime panics. Use plain references first; reserve Box, Rc, and Arc for recursive types, shared ownership, or threads.

Next, try these patterns directly in the browser or move straight to the command-line project below.

Practice Rust

Compile, run, and test real Rust code right in your browser without installing anything. The practice environment below runs unmodified rustc 1.96.1 (Rust 2024 edition) with std and rustc --test, and mounts the sample events.log file in the working directory. Nothing downloads until you press Start (about 45 MB once per visit), and there is no network connection inside the sandbox. Choose Open full screen to give the editor the whole window.

The exercise list holds eight tasks drawn from the patterns above and from Brenden Matthews’ Idiomatic Rust:

  1. Fix an E0382 borrow-of-moved-value error by borrowing &str instead of cloning.
  2. Refactor average from &Vec<f64> to a slice &[f64] so it works on both vectors and arrays.
  3. Replace .unwrap() calls with a custom ConfigError enum, From, and ?.
  4. Add LatencyMs::as_millis(&self) and implement Reportable for Endpoint.
  5. Compute slow-request totals and counts with borrowed .iter().copied() pipelines.
  6. Remove an unnecessary .clone() trap by borrowing a slice.
  7. Parse events.log with BufReader and summarize counts and slowest paths in a BTreeMap.
  8. Fix and run #[cfg(test)] unit tests in Test mode.

Pick an exercise to load its starting main.rs, edit the code, and press Run, Test, or Check. Hint and Show answer teach in place when you get stuck, and Reset restores the starting code.

Every example also compiles locally with cargo run and cargo test. Because this browser sandbox runs single-file rustc with no network adapter, a few things require your own machine:

  • Cargo projects and external crates. cargo new, cargo fmt, cargo clippy, and crates from crates.io (such as serde, tokio, or clap) are not available here; only std, core, and alloc ship in the sandbox.
  • Networking. There is no network interface inside the sandbox, so std::net calls cannot reach external hosts.
  • Persistent files. Each Run or Test starts in a clean working directory containing a fresh copy of events.log; files you write do not persist across runs.
  • 64-bit targets and large builds. The guest runs 32-bit Linux (i586-alpine-linux-musl) in 256 MB of memory, with a 10-second execution limit and a 60-second compile-and-run guard.

Practice the commands on this page in real rustc, right here. Nothing downloads until Start (about 45 MB).

Each exercise loads a small Rust program into main.rs. Some fail to compile with a real borrow-checker or type error, some panic at runtime, and some break an idiomatic Rust rule. Edit the code until Run (or Test) and Check pass. Hint and Show answer stay on this page when you get stuck.

Own your data and let RAII clean it up
  1  Fix the borrow-of-moved-value error (E0382) without cloning

Borrow by default, and prefer slices over owned collections
  2  Refactor average to accept a slice so it works on both Vec and arrays

Replace null and exceptions with Option, Result, and ?
  3  Replace .unwrap() with ConfigError, From, and ?

Share behavior with traits, generics, and newtypes
  4  Add LatencyMs::as_millis and implement Reportable for Endpoint

Transform collections with iterators and closures
  5  Compute slow request count and total with borrowed iterators

Avoid the five common Rust traps
  6  Remove the unnecessary .clone() by borrowing a slice

Build Something: A Verified Log Summary CLI
  7  Parse events.log with BufReader and summarize counts and slowest path by level
  8  Fix the unit tests for parse_line and pass them in Test mode

The Rust practice needs JavaScript. Every command in the reference also works in rustc on your own machine.

Build Something: A Verified Log Summary CLI

Build a zero-dependency CLI log analyzer that combines ownership, slices, custom errors with ?, newtypes, BTreeMap, and unit tests. Confirm rustc --version and cargo --version work in your terminal before starting; this build takes about 15 minutes.

Step 1: Create the Cargo project and sample log

Create a new binary project and move into its folder:

Runs on your machine, not in the practice shell

cargo new log-summary
cd log-summary

Create a sample log file named events.log in the project root with five valid entries and one intentionally broken line (on Windows, or in a text editor, save the six lines between EOF markers as events.log next to Cargo.toml):

Runs on your machine, not in the practice shell

cat <<'EOF' > events.log
INFO /health 12
WARN /search 185
ERROR /checkout 420
INFO /items 34
ERROR /checkout 510
MALFORMED LINE
EOF

Step 2: Implement typed parsing and aggregation, then check the build

Replace src/main.rs with the program below. Each function accepts borrowed slices (&str, &[LogEntry], &Path), File closes through RAII when load_entries returns, and LogError converts std::io::Error via From:

use std::collections::BTreeMap;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::num::ParseIntError;
use std::path::Path;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Level {
    Info,
    Warn,
    Error,
}

impl fmt::Display for Level {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Info => "INFO",
            Self::Warn => "WARN",
            Self::Error => "ERROR",
        };
        write!(f, "{name}")
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct LatencyMs(u64);

impl LatencyMs {
    fn as_millis(&self) -> u64 {
        self.0
    }
}

#[derive(Debug, PartialEq, Eq)]
struct LogEntry {
    level: Level,
    path: String,
    latency: LatencyMs,
}

#[derive(Debug)]
enum LogError {
    Io(std::io::Error),
    BadFormat { line_number: usize },
    UnknownLevel { line_number: usize, value: String },
    BadLatency { line_number: usize, source: ParseIntError },
}

impl fmt::Display for LogError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(err) => write!(f, "I/O error: {err}"),
            Self::BadFormat { line_number } => {
                write!(f, "line {line_number}: expected '<LEVEL> <PATH> <MS>'")
            }
            Self::UnknownLevel { line_number, value } => {
                write!(f, "line {line_number}: unknown level '{value}'")
            }
            Self::BadLatency { line_number, source } => {
                write!(f, "line {line_number}: invalid latency: {source}")
            }
        }
    }
}

impl std::error::Error for LogError {}

impl From<std::io::Error> for LogError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}

fn parse_line(line: &str, line_number: usize) -> Result<LogEntry, LogError> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() != 3 {
        return Err(LogError::BadFormat { line_number });
    }

    let level = match parts[0] {
        "INFO" => Level::Info,
        "WARN" => Level::Warn,
        "ERROR" => Level::Error,
        other => {
            return Err(LogError::UnknownLevel {
                line_number,
                value: other.to_string(),
            });
        }
    };

    let ms: u64 = parts[2].parse().map_err(|source| LogError::BadLatency {
        line_number,
        source,
    })?;

    Ok(LogEntry {
        level,
        path: parts[1].to_string(),
        latency: LatencyMs(ms),
    })
}

#[derive(Debug, Default, PartialEq, Eq)]
struct LevelStats {
    count: usize,
    max_latency: Option<LatencyMs>,
    slowest_path: String,
}

fn summarize(entries: &[LogEntry]) -> BTreeMap<Level, LevelStats> {
    let mut stats: BTreeMap<Level, LevelStats> = BTreeMap::new();
    for entry in entries {
        let bucket = stats.entry(entry.level).or_default();
        bucket.count += 1;
        let is_slower = match bucket.max_latency {
            Some(current) => entry.latency > current,
            None => true,
        };
        if is_slower {
            bucket.max_latency = Some(entry.latency);
            bucket.slowest_path = entry.path.clone();
        }
    }
    stats
}

fn load_entries(path: &Path) -> Result<(Vec<LogEntry>, Vec<LogError>), LogError> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);
    let mut entries = Vec::new();
    let mut errors = Vec::new();

    for (index, line_result) in reader.lines().enumerate() {
        let line = line_result?;
        if line.trim().is_empty() {
            continue;
        }
        match parse_line(&line, index + 1) {
            Ok(entry) => entries.push(entry),
            Err(err) => errors.push(err),
        }
    }

    Ok((entries, errors))
}

fn main() -> Result<(), LogError> {
    let (entries, errors) = load_entries(Path::new("events.log"))?;
    let summary = summarize(&entries);

    for (level, stats) in &summary {
        let max_ms = stats.max_latency.map_or(0, |l| l.as_millis());
        let noun = if stats.count == 1 { "event" } else { "events" };
        println!(
            "{level}: {} {noun} (slowest: {max_ms} ms on {})",
            stats.count, stats.slowest_path
        );
    }

    if !errors.is_empty() {
        println!("Skipped {} malformed line(s):", errors.len());
        for err in &errors {
            println!("  - {err}");
        }
    }

    Ok(())
}

Verify that types, borrowing, and error conversions compile cleanly:

Runs on your machine, not in the practice shell

cargo check

cargo check prints Finished with zero warnings.

Three standard-library pieces drive the core logic above:

  • BufReader::new(file).lines() streams the file line by line without loading the whole file into memory.
  • stats.entry(entry.level).or_default() looks up a BTreeMap bucket and initializes LevelStats::default() only on the first sighting of a level.
  • fn main() -> Result<(), LogError> propagates file I/O errors with ? and prints the error in Debug format when main exits with Err.

Step 3: Add unit tests, run, and lint the program

Append the #[cfg(test)] unit test module to the bottom of src/main.rs. The #[cfg(test)] attribute compiles this module only during cargo test, and matches! asserts enum error variants without boilerplate:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_valid_log_line() {
        let entry = parse_line("WARN /search 185", 2).expect("valid line should parse");
        assert_eq!(entry.level, Level::Warn);
        assert_eq!(entry.path, "/search");
        assert_eq!(entry.latency, LatencyMs(185));
    }

    #[test]
    fn rejects_unknown_level() {
        let err = parse_line("DEBUG /search 12", 1).expect_err("DEBUG should fail");
        assert!(matches!(err, LogError::UnknownLevel { line_number: 1, .. }));
    }

    #[test]
    fn summarizes_counts_and_max_latency() {
        let entries = vec![
            parse_line("ERROR /checkout 420", 1).expect("valid"),
            parse_line("ERROR /checkout 510", 2).expect("valid"),
        ];
        let stats = summarize(&entries);
        let error_stats = stats.get(&Level::Error).expect("ERROR bucket missing");
        assert_eq!(error_stats.count, 2);
        assert_eq!(error_stats.max_latency, Some(LatencyMs(510)));
        assert_eq!(error_stats.slowest_path, "/checkout");
    }
}

Run the CLI against events.log:

Runs on your machine, not in the practice shell

cargo run --quiet

Expected output:

INFO: 2 events (slowest: 34 ms on /items)
WARN: 1 event (slowest: 185 ms on /search)
ERROR: 2 events (slowest: 510 ms on /checkout)
Skipped 1 malformed line(s):
  - line 6: expected '<LEVEL> <PATH> <MS>'

Run the test suite to verify valid parsing, error rejection, and aggregation:

Runs on your machine, not in the practice shell

cargo test --quiet

Expected output:

running 3 tests
...
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Check formatting and idioms (both tools ship with the default rustup profile):

Runs on your machine, not in the practice shell

cargo fmt --check
cargo clippy

cargo fmt --check exits silently with status 0 when formatting matches rustfmt defaults. cargo clippy prints Finished with zero warnings.

What you learned: You built an idiomatic Rust CLI with zero .unwrap() calls in application code and automatic file cleanup through RAII. It enforces unit safety with LatencyMs, keeps output ordered in a BTreeMap, and ships with built-in unit tests.

To clean up after finishing, return to the parent directory and remove the project folder (cd .. && rm -rf log-summary on macOS/Linux, or cd ..; Remove-Item -Recurse -Force log-summary in PowerShell). To remove the Rust toolchain later, run rustup self uninstall.

Troubleshooting

For any compiler code not listed below, run rustc --explain <code> (for example, rustc --explain E0382) to read the built-in documentation and minimal fix example.

error: linker 'cc' not found

Cargo compiled your Rust code but could not find a system C linker to produce the executable. Install Xcode Command Line Tools (xcode-select --install) on macOS, build-essential on Debian/Ubuntu, or the C++ Build Tools workload in Visual Studio Installer on Windows. Then run cargo run again.

Error: Io(Os { code: 2, kind: NotFound, message: "No such file or directory" })

cargo run looked for events.log in your current working directory and could not find it. Confirm you are inside the log-summary folder (pwd) and that events.log sits beside Cargo.toml. (On Windows, the message reads “The system cannot find the file specified.” with the same kind: NotFound.)

error[E0382]: borrow of moved value

A non-Copy value (such as String or Vec<T>) moved into a function or another binding, and later code tried to read the old variable. Change the function parameter to borrow (&str or &[T]) instead of taking ownership. Only call .clone() when both owners truly need separate heap copies.

error[E0502]: cannot borrow as mutable because it is also borrowed as immutable

An immutable reference (&x) is still used after a mutable borrow (&mut x) begins. Finish reading through the immutable reference before starting the mutable borrow, or shorten the immutable borrow’s scope with a block { ... }.

error[E0277]: '?' couldn't convert the error

The function uses ? on a Result<T, SourceError>, but its own return type uses a different TargetError without a conversion. Implement From<SourceError> for TargetError, or convert explicitly at the call site with .map_err(...).

error[E0308]: mismatched types (expected T, found ())

You placed a trailing semicolon ; on the final expression of a function, turning it into a statement that returns unit (). Remove the semicolon on the returned expression, or add return.

error[E0599]: no method named ... found

Methods defined on a trait (such as .lines() from std::io::BufRead or .write_all() from std::io::Write) are available only when that trait is in scope. Add the use import suggested by the compiler’s help: line, or add the missing trait bound to your generic type parameter.

Learn Rust: Beyond the Basics

You have the core patterns in hand. Work through an interactive book or exercise track daily for two weeks, then deepen your mental model with a focused idiomatic patterns book.

Video

  • Learn Rust Programming: Complete Course on freeCodeCamp (YouTube). Full beginner-to-intermediate video course paired with Rust by Practice exercises.
  • Crust of Rust by Jon Gjengset on YouTube. Live-coded sessions on lifetimes, iterators, smart pointers, traits, and concurrency once you finish the basics.
  • Interview and AMA with Josh Triplett on YouTube. The Rust language team co-lead explains design trade-offs, Cargo, and where the language is heading.

Audio

  • Rustacean Station. Community podcast covering Rust releases, crate walkthroughs, and interviews with library authors.
  • New Rustacean. Archived, concept-by-concept audio series that walks through ownership, traits, and error handling without requiring a screen.

Books

  • Idiomatic Rust: Code Like a Rustacean by Brenden Matthews (Manning, 2024). Practical patterns, library ergonomics, and antipatterns for writing native-feeling Rust.
  • The Rust Programming Language by Steve Klabnik and Carol Nichols. The official book, free online; use the Brown University interactive edition for built-in ownership quizzes and memory visualizations.
  • Programming Rust by Jim Blandy, Jason Orendorff, and Leonora Tindall (O’Reilly). Systems-level explanations of memory layout, traits, concurrency, and unsafe code.
  • Rust for Rustaceans by Jon Gjengset (No Starch Press). Best second book once you have shipped a few crates and want to master type design, macros, and async internals.

Online

  • Rust Playground. Official browser sandbox for compiling and testing standard-library Rust snippets with Clippy and Miri.
  • Rust by Example. Official collection of short, runnable annotated examples covering syntax and standard library types.
  • Comprehensive Rust. Google’s free multi-day training course covering core Rust, concurrency, Android, and bare-metal programming.
  • Rustlings. Small broken exercises maintained by the Rust project that train you to read and fix compiler diagnostics locally.
  • Exercism Rust Track. Practice problems solved with your local toolchain, backed by automated tests and optional human mentoring.
  • Memory Analysis in Rust. Practical guide to profiling memory usage and tracking down leaks in real Rust applications.
  • Migrating from Go to Rust. Practical guide for developers moving from Go’s garbage collector and interfaces to Rust’s ownership and traits.

References