Five articles on this site make claims about code that compiles cleanly:

This page is the evidence: the code, the toolchain, and the output of every command. It was checked on with Rust 1.100.0.

The output is unedited, except that:

  • the temporary directory the crate is built in is shown as /tmp/article-examples;
  • timings, and the hash Cargo adds to the test program’s name and directory, are left out, because they change from run to run without anything else changing;
  • each test run lists its tests in name order, rather than in the order they happened to finish, and does not say how many of the crate’s other tests it skipped.

A small Rust tool in the site’s repository rebuilds the examples, fails if any claim on this page no longer holds, and records the results. The site is built from those records, and each article’s section appears in the same build as the article, not before. The tool also checks that every Rust snippet in an article is part of that article’s module in the code it compiles. A weekly job runs the same checks against the latest stable Rust.

What this shows, and what it does not

It shows that, with the toolchain and edition below, none of these examples produces a warning from the compiler or from Clippy’s default lints, and that the tests pass.

It does not mean the patterns go unnoticed by every tool. With the whole pedantic group and the unwrap_used and expect_used lints switched on, Clippy flags some of them. Each article’s section below lists what those lints flag in its code, and what they miss. pedantic also asks for # Errors and # Panics sections and #[must_use] attributes, which are documentation points rather than design ones, so they are not listed. The patterns the lints miss still need a person who understands why they are a problem. Later versions of Rust and Clippy may add warnings for some of them, which is why each article shows the Rust version it was written with and the version its examples were last checked with.

The code

One library crate, with a module for each article. Its src/lib.rs declares the modules, and each article’s module is shown in that article’s section below.

Cargo.toml:

[package]
name = "article-examples"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]

clippy.toml lets tests use unwrap() and expect() when the opt-in lints that forbid them elsewhere are switched on, as the reviewing article suggests. It has no effect on Clippy’s default lints.

allow-unwrap-in-tests = true
allow-expect-in-tests = true

The toolchain

$ rustc --version
rustc 1.100.0 (0ef1bc386 2026-11-09)
$ cargo --version
cargo 1.100.0 (3acc79c0c 2026-11-05)
$ cargo clippy --version
clippy 0.1.100 (0ef1bc3860 2026-11-09)

rustc

Compiling the crate directly with rustc printed nothing at all and exited with status 0, which means no warnings and no errors.

$ rustc --edition 2024 --crate-type lib --out-dir target src/lib.rs

Cargo

The same result through Cargo, building the library and its tests from clean:

$ cargo build --all-targets
   Compiling article-examples v0.1.0 (/tmp/article-examples)
    Finished `dev` profile [unoptimized + debuginfo] target(s)

Clippy, default lints

$ cargo clippy --all-targets
    Checking article-examples v0.1.0 (/tmp/article-examples)
    Finished `dev` profile [unoptimized + debuginfo] target(s)

Tests

Every test in the crate passes. Each article’s tests are also run on their own, filtered to its module, and shown in its section below.

Why learn Rust when an AI can write it?

The article says that four common patterns in AI-written Rust compile without a murmur, and that cargo clippy with its default settings says nothing about them either.

Code

src/why_learn.rs:

//! The four patterns from "Why learn Rust when an AI can write it?", written
//! the way an assistant typically produces them.

use std::sync::{Arc, Mutex};

/// 1. A function that clones a vector because borrowing it was awkward.
pub fn count_long(names: Vec<String>) -> usize {
    names.iter().filter(|name| name.len() > 5).count()
}

pub fn report_long_names(names: Vec<String>) -> String {
    // The caller still needs `names` afterwards, so the move is "fixed" with a clone.
    let long = count_long(names.clone());
    format!("{long} of {} names are long", names.len())
}

/// 2. A parser that calls unwrap() and takes the whole process down on bad input.
pub fn parse_port(input: &str) -> u16 {
    input.trim().parse().unwrap()
}

/// 3. A library that reports every failure as a String.
pub fn parse_config_line(line: &str) -> Result<(String, u16), String> {
    let (key, value) = line
        .split_once('=')
        .ok_or_else(|| format!("missing '=' in {line:?}"))?;
    let port = value
        .trim()
        .parse()
        .map_err(|e| format!("bad port {value:?}: {e}"))?;
    Ok((key.trim().to_string(), port))
}

/// 4. Shared state wrapped in Arc<Mutex<_>> in code that never leaves one thread.
pub fn word_count(text: &str) -> usize {
    let count = Arc::new(Mutex::new(0));
    for _word in text.split_whitespace() {
        *count.lock().unwrap() += 1;
    }
    *count.lock().unwrap()
}

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

    #[test]
    fn the_patterns_behave_as_described() {
        let names = vec!["Ada".to_string(), "Grace Hopper".to_string()];
        assert_eq!(report_long_names(names), "1 of 2 names are long");
        assert_eq!(parse_port(" 8080 "), 8080);
        assert!(std::panic::catch_unwind(|| parse_port("http")).is_err());
        let (key, port) = parse_config_line("web = 80").expect("a valid line");
        assert_eq!((key.as_str(), port), ("web", 80));
        assert!(
            parse_config_line("web")
                .unwrap_err()
                .contains("missing '='")
        );
        assert_eq!(word_count(" a  b c\n"), 3);
    }
}

Tests

$ cargo test --lib why_learn::
    Finished `test` profile [unoptimized + debuginfo] target(s)
     Running unittests src/lib.rs (target/debug/build/article-examples/HASH/out/article_examples-HASH)

running 1 test
test why_learn::tests::the_patterns_behave_as_described ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

Opt-in lints

With the whole pedantic group and the unwrap_used and expect_used lints switched on, Clippy flags:

  • clippy::needless_pass_by_value on why_learn::count_long
  • clippy::needless_pass_by_value on why_learn::report_long_names
  • clippy::unwrap_used on why_learn::parse_port
  • clippy::unwrap_used on why_learn::word_count

clippy::needless_pass_by_value, in the pedantic group, flags count_long and report_long_names, which take a Vec<String> they only read. clippy::unwrap_used, in the restriction group, flags the unwrap() calls in parse_port and word_count.

Nothing in those lints objects to the String errors from parse_config_line, or to the unnecessary Arc<Mutex<_>> in word_count. Those patterns still need a person who understands why they are a problem. The test checks that each pattern behaves as the article describes, including parse_port panicking on "http".

Reviewing AI-written Rust: six things to check

The article says that its “before” examples compile without a murmur and that cargo clippy with its default settings says nothing about them either, and that its “after” examples compile and pass their tests.

Code

src/reviewing.rs:

//! The examples from "Reviewing AI-written Rust: six things to check".

/// The "before" examples: what an assistant typically writes.
pub mod before {
    use std::sync::{Arc, Mutex};

    pub fn count_long(names: Vec<String>) -> usize {
        names.iter().filter(|name| name.len() > 5).count()
    }

    pub fn print_long_names() -> usize {
        let names = vec!["Ada".to_string(), "Grace Hopper".to_string()];
        let long = count_long(names.clone());
        println!("{long} of {} names are long", names.len());
        long
    }

    pub fn parse_port(input: &str) -> u16 {
        input.trim().parse().unwrap()
    }

    #[derive(Debug, Clone, PartialEq)]
    pub struct User {
        pub id: u32,
        pub name: String,
    }

    pub fn find_user(users: &[User], id: u32) -> Option<User> {
        users.iter().find(|user| user.id == id).cloned()
    }

    pub fn word_count(text: &str) -> usize {
        let count = Arc::new(Mutex::new(0));
        for _word in text.split_whitespace() {
            *count.lock().unwrap() += 1;
        }
        *count.lock().unwrap()
    }
}

/// The "errors as strings" example, which has no direct "after" version.
pub mod strings {
    pub fn parse_port(input: &str) -> Result<u16, String> {
        input
            .trim()
            .parse()
            .map_err(|e| format!("bad port {input:?}: {e}"))
    }
}

/// The "after" examples: what to ask for instead.
pub mod after {
    use std::num::ParseIntError;

    #[derive(Debug, PartialEq, Eq)]
    pub enum PortError {
        NotANumber(ParseIntError),
        Zero,
    }

    pub fn parse_port(input: &str) -> Result<u16, PortError> {
        match input.trim().parse() {
            Ok(0) => Err(PortError::Zero),
            Ok(port) => Ok(port),
            Err(e) => Err(PortError::NotANumber(e)),
        }
    }

    pub fn count_long(names: &[String]) -> usize {
        names.iter().filter(|name| name.len() > 5).count()
    }

    pub fn print_long_names() -> usize {
        let names = vec!["Ada".to_string(), "Grace Hopper".to_string()];
        let long = count_long(&names);
        println!("{long} of {} names are long", names.len());
        long
    }

    #[derive(Debug, PartialEq)]
    pub struct User {
        pub id: u32,
        pub name: String,
    }

    pub fn find_user(users: &[User], id: u32) -> Option<&User> {
        users.iter().find(|user| user.id == id)
    }

    pub fn word_count(text: &str) -> usize {
        text.split_whitespace().count()
    }

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

        #[test]
        fn parses_port() {
            assert_eq!(parse_port("8080"), Ok(8080));
        }

        #[test]
        fn trims_surrounding_whitespace() {
            assert_eq!(parse_port(" 443\n"), Ok(443));
        }

        #[test]
        fn rejects_port_zero() {
            assert_eq!(parse_port("0"), Err(PortError::Zero));
        }

        #[test]
        fn rejects_empty_and_out_of_range_input() {
            assert!(matches!(parse_port(""), Err(PortError::NotANumber(_))));
            assert!(matches!(parse_port("65536"), Err(PortError::NotANumber(_))));
            assert!(matches!(parse_port("-1"), Err(PortError::NotANumber(_))));
        }

        #[test]
        fn finds_a_user_by_reference() {
            let users = vec![User {
                id: 1,
                name: "Ada".into(),
            }];
            assert_eq!(
                find_user(&users, 1).map(|user| user.name.as_str()),
                Some("Ada")
            );
            assert_eq!(find_user(&users, 2), None);
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn before_and_after_agree_where_the_input_is_valid() {
        assert_eq!(
            super::before::print_long_names(),
            super::after::print_long_names()
        );
        assert_eq!(super::before::parse_port("8080"), 8080);
        assert_eq!(super::strings::parse_port("8080"), Ok(8080));
        assert_eq!(
            super::before::word_count(" a  b c\n"),
            super::after::word_count(" a  b c\n")
        );
        let users = vec![super::before::User {
            id: 1,
            name: "Ada".into(),
        }];
        assert_eq!(
            super::before::find_user(&users, 1).map(|user| user.name),
            Some("Ada".to_string())
        );
    }

    #[test]
    fn before_parse_port_panics_on_bad_input() {
        assert!(std::panic::catch_unwind(|| super::before::parse_port("http")).is_err());
    }

    #[test]
    fn strings_parse_port_reports_a_message() {
        let error = super::strings::parse_port("http").expect_err("not a number");
        assert!(error.starts_with("bad port \"http\""));
    }
}

Tests

$ cargo test --lib reviewing::
    Finished `test` profile [unoptimized + debuginfo] target(s)
     Running unittests src/lib.rs (target/debug/build/article-examples/HASH/out/article_examples-HASH)

running 8 tests
test reviewing::after::tests::finds_a_user_by_reference ... ok
test reviewing::after::tests::parses_port ... ok
test reviewing::after::tests::rejects_empty_and_out_of_range_input ... ok
test reviewing::after::tests::rejects_port_zero ... ok
test reviewing::after::tests::trims_surrounding_whitespace ... ok
test reviewing::tests::before_and_after_agree_where_the_input_is_valid ... ok
test reviewing::tests::before_parse_port_panics_on_bad_input ... ok
test reviewing::tests::strings_parse_port_reports_a_message ... ok

test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured

Opt-in lints

With the whole pedantic group and the unwrap_used and expect_used lints switched on, Clippy flags:

  • clippy::needless_pass_by_value on reviewing::before::count_long
  • clippy::unwrap_used on reviewing::before::parse_port
  • clippy::unwrap_used on reviewing::before::word_count

clippy::needless_pass_by_value, in the pedantic group, flags the “before” count_long, which takes a Vec<String> it only reads. clippy::unwrap_used, in the restriction group, flags the unwrap() calls in the “before” parse_port and word_count.

Nothing in those lints objects to the String errors from strings::parse_port, to the “before” find_user returning a cloned User, or to the unnecessary Arc<Mutex<_>> in the “before” word_count. Those patterns still need a person who understands why they are a problem. The tests check that each example behaves as the article describes, including the “before” parse_port panicking on "http" and the “after” parse_port rejecting 0, 65536 and -1.

When is a clone the right answer?

The article says that every example compiles without warnings, and that Clippy’s default lints say nothing about any of them.

Code

src/when_to_clone.rs:

//! The examples from "When is a clone the right answer?".

use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::thread::{self, JoinHandle};

/// What a clone copies: all the data for a `String`, a pointer for an `Arc`.
pub fn clone_both() -> (String, String, Arc<String>, Arc<String>) {
    let text = String::from("a long document");
    let copy = text.clone();

    let shared = Arc::new(String::from("a long document"));
    let handle = Arc::clone(&shared);
    (text, copy, shared, handle)
}

#[derive(Clone, Debug, PartialEq)]
pub struct Settings {
    pub endpoint: String,
    pub retries: u32,
}

pub struct Client {
    settings: Settings,
}

impl Client {
    pub fn new(settings: Settings) -> Self {
        Self { settings }
    }
}

impl Client {
    pub fn settings(&self) -> &Settings {
        &self.settings
    }
}

/// Two clients, each keeping its own settings.
pub fn make_clients(settings: Settings) -> (Client, Client) {
    let primary = Client::new(settings.clone());
    let fallback = Client::new(settings);
    (primary, fallback)
}

pub fn spawn_reporter(settings: Arc<Settings>) -> JoinHandle<String> {
    thread::spawn(move || format!("reporting to {}", settings.endpoint))
}

/// The caller keeps its handle, so it clones the `Arc` for the thread.
pub fn start_reporter(settings: Settings) -> (Arc<Settings>, JoinHandle<String>) {
    let shared = Arc::new(settings);
    let reporter = spawn_reporter(Arc::clone(&shared));
    (shared, reporter)
}

pub struct Scheduler {
    jobs: Vec<String>,
    log: Vec<String>,
}

impl Scheduler {
    fn run(&mut self, job: &str) {
        self.log.push(format!("ran {job}"));
        if job == "build" {
            self.jobs.push("test".to_string());
        }
    }

    pub fn run_all(&mut self) {
        for job in self.jobs.clone() {
            self.run(&job);
        }
    }
}

impl Scheduler {
    pub fn with_jobs(jobs: &[&str]) -> Self {
        Self {
            jobs: jobs.iter().map(|job| (*job).to_string()).collect(),
            log: Vec::new(),
        }
    }

    pub fn jobs(&self) -> &[String] {
        &self.jobs
    }

    pub fn log(&self) -> &[String] {
        &self.log
    }
}

pub fn expand_tabs(input: &str) -> Cow<'_, str> {
    if input.contains('\t') {
        Cow::Owned(input.replace('\t', "    "))
    } else {
        Cow::Borrowed(input)
    }
}

pub fn tally(words: &[String]) -> HashMap<String, usize> {
    let mut counts = HashMap::new();
    for word in words {
        *counts.entry(word.clone()).or_insert(0) += 1;
    }
    counts
}

/// The alternative the article describes in words: look the word up first,
/// and clone it only when it is new.
pub fn tally_distinct(words: &[String]) -> HashMap<String, usize> {
    let mut counts: HashMap<String, usize> = HashMap::new();
    for word in words {
        if let Some(count) = counts.get_mut(word.as_str()) {
            *count += 1;
        } else {
            counts.insert(word.clone(), 1);
        }
    }
    counts
}

/// Counts heap allocations made on the current thread, so that the tests can
/// show which clones allocate.
///
/// The counts are observations, not language guarantees: the compiler is
/// allowed to remove or merge allocations. They hold for the unoptimised
/// `cargo test` build that the compile check runs, on the toolchain named on
/// the compile check page.
#[cfg(test)]
mod allocations {
    use std::alloc::{GlobalAlloc, Layout, System};
    use std::cell::Cell;

    thread_local! {
        static COUNT: Cell<usize> = const { Cell::new(0) };
    }

    struct Counting;

    // SAFETY: every call is forwarded unchanged to the system allocator, and
    // the bookkeeping neither allocates nor panics.
    unsafe impl GlobalAlloc for Counting {
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            let _ = COUNT.try_with(|count| count.set(count.get().wrapping_add(1)));
            // SAFETY: the caller upholds the contract of `GlobalAlloc::alloc`.
            unsafe { System.alloc(layout) }
        }

        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
            // SAFETY: the caller upholds the contract of `GlobalAlloc::dealloc`.
            unsafe { System.dealloc(ptr, layout) }
        }
    }

    #[global_allocator]
    static GLOBAL: Counting = Counting;

    /// Runs `f` and returns its result with the number of allocations it made
    /// on the current thread.
    pub fn count<T>(f: impl FnOnce() -> T) -> (T, usize) {
        let before = COUNT.with(Cell::get);
        let value = f();
        (value, COUNT.with(Cell::get).wrapping_sub(before))
    }
}

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

    fn settings() -> Settings {
        Settings {
            endpoint: "https://example.com/report".to_string(),
            retries: 3,
        }
    }

    #[test]
    fn cloning_a_string_copies_the_data() {
        let (text, copy, _, _) = clone_both();
        assert_eq!(copy, text);
        assert_ne!(copy.as_ptr(), text.as_ptr());

        let (_, allocations) = count(|| text.clone());
        assert_eq!(allocations, 1);
    }

    #[test]
    fn cloning_an_arc_copies_a_pointer() {
        let (_, _, shared, handle) = clone_both();
        assert!(Arc::ptr_eq(&shared, &handle));
        assert_eq!(Arc::strong_count(&shared), 2);

        let (_, allocations) = count(|| Arc::clone(&shared));
        assert_eq!(allocations, 0);
    }

    #[test]
    fn cloning_a_vec_of_arcs_shares_the_elements() {
        let original = vec![Arc::new("shared".to_string())];
        let copy = original.clone();
        assert!(Arc::ptr_eq(&original[0], &copy[0]));
        assert_ne!(original.as_ptr(), copy.as_ptr());
    }

    #[test]
    fn cloning_settings_allocates_once_for_its_string() {
        let settings = settings();
        let (copy, allocations) = count(|| settings.clone());
        assert_eq!(copy, settings);
        assert_eq!(allocations, 1);
    }

    #[test]
    fn each_client_has_its_own_settings() {
        let (primary, fallback) = make_clients(settings());
        assert_eq!(primary.settings(), fallback.settings());
        assert_ne!(
            primary.settings().endpoint.as_ptr(),
            fallback.settings().endpoint.as_ptr()
        );
    }

    #[test]
    fn the_reporter_thread_owns_a_handle_to_the_settings() {
        let (shared, reporter) = start_reporter(settings());
        let report = reporter.join().expect("the reporter thread panicked");
        assert_eq!(report, "reporting to https://example.com/report");
        // The thread's handle was dropped when it finished.
        assert_eq!(Arc::strong_count(&shared), 1);
    }

    #[test]
    fn run_all_runs_a_snapshot_of_the_jobs() {
        let mut scheduler = Scheduler::with_jobs(&["build", "deploy"]);
        scheduler.run_all();
        assert_eq!(scheduler.log(), ["ran build", "ran deploy"]);
        assert_eq!(scheduler.jobs(), ["build", "deploy", "test"]);

        scheduler.run_all();
        assert_eq!(scheduler.log().last().map(String::as_str), Some("ran test"));
    }

    #[test]
    fn expand_tabs_borrows_when_nothing_changes() {
        let (result, allocations) = count(|| expand_tabs("no tabs here"));
        assert!(matches!(result, Cow::Borrowed("no tabs here")));
        assert_eq!(allocations, 0);
    }

    #[test]
    fn expand_tabs_allocates_when_it_must() {
        let result = expand_tabs("a\tb");
        assert!(matches!(result, Cow::Owned(_)));
        assert_eq!(result, "a    b");
    }

    #[test]
    fn tally_clones_every_word_and_get_mut_first_clones_each_distinct_word() {
        let words = vec!["same".to_string(); 1000];
        let (every, every_allocations) = count(|| tally(&words));
        let (distinct, distinct_allocations) = count(|| tally_distinct(&words));
        assert_eq!(every, distinct);
        assert_eq!(every.get("same"), Some(&1000));
        assert!(every_allocations >= 1000);
        assert!(distinct_allocations < 10);
    }

    #[test]
    fn tally_counts_each_word() {
        let words: Vec<String> = ["a", "b", "a"].iter().map(|w| (*w).to_string()).collect();
        let counts = tally(&words);
        assert_eq!(counts.get("a"), Some(&2));
        assert_eq!(counts.get("b"), Some(&1));
    }
}

Tests

$ cargo test --lib when_to_clone::
    Finished `test` profile [unoptimized + debuginfo] target(s)
     Running unittests src/lib.rs (target/debug/build/article-examples/HASH/out/article_examples-HASH)

running 11 tests
test when_to_clone::tests::cloning_a_string_copies_the_data ... ok
test when_to_clone::tests::cloning_a_vec_of_arcs_shares_the_elements ... ok
test when_to_clone::tests::cloning_an_arc_copies_a_pointer ... ok
test when_to_clone::tests::cloning_settings_allocates_once_for_its_string ... ok
test when_to_clone::tests::each_client_has_its_own_settings ... ok
test when_to_clone::tests::expand_tabs_allocates_when_it_must ... ok
test when_to_clone::tests::expand_tabs_borrows_when_nothing_changes ... ok
test when_to_clone::tests::run_all_runs_a_snapshot_of_the_jobs ... ok
test when_to_clone::tests::tally_clones_every_word_and_get_mut_first_clones_each_distinct_word ... ok
test when_to_clone::tests::tally_counts_each_word ... ok
test when_to_clone::tests::the_reporter_thread_owns_a_handle_to_the_settings ... ok

test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured

Opt-in lints

With the whole pedantic group and the unwrap_used and expect_used lints switched on, Clippy flags nothing in this article’s code apart from the documentation lints.

The tests check what the article says each clone does: that cloning a String copies its data, that cloning an Arc copies a pointer, that cloning a Vec of Arcs shares the elements, and that expand_tabs borrows its input when nothing needs to change. Some tests count heap allocations. Those counts are observations of this build, not guarantees: the compiler is allowed to remove or merge allocations.

Read the compiler error before you paste it into a chat

The article says that the fixed versions of its examples compile without warnings and that Clippy’s default lints say nothing about them, and that applying the compiler’s own .clone() suggestion also compiles.

Code

src/compiler_errors.rs:

//! The examples from "Read the compiler error before you paste it into a chat".
//!
//! The article's examples that fail to compile are not here, because this
//! crate must build. The article shows them, and their errors, as text.

/// The compiler's `.clone()` suggestion for the moved vector, applied as
/// written. It compiles, but the function still asks to own a vector it only
/// reads.
pub mod suggested {
    pub fn longest_line(lines: Vec<String>) -> usize {
        lines.iter().map(String::len).max().unwrap_or(0)
    }

    pub fn report() -> String {
        let lines = vec![String::from("compile"), String::from("read the error")];
        let width = longest_line(lines.clone());
        format!("{} lines, the longest is {width} bytes", lines.len())
    }
}

/// The fix the compiler's note points at: borrow instead of taking ownership.
pub fn longest_line(lines: &[String]) -> usize {
    lines.iter().map(String::len).max().unwrap_or(0)
}

/// The same shape as the failing program: the caller still uses its vector
/// after the call.
pub fn report() -> String {
    let lines = vec![String::from("compile"), String::from("read the error")];
    let width = longest_line(&lines);
    format!("{} lines, the longest is {width} bytes", lines.len())
}

/// First fix for the queue: finish with the borrow before changing the vector.
pub fn use_then_push() -> Vec<String> {
    let mut queue = vec![String::from("build"), String::from("test")];
    let next = &queue[0];
    println!("next up: {next}");
    queue.push(String::from("deploy"));
    queue
}

/// Second fix for the queue: take an owned copy of one element, so that it
/// can outlive the push.
pub fn copy_then_push() -> (String, Vec<String>) {
    let mut queue = vec![String::from("build"), String::from("test")];
    let next = queue[0].clone();
    queue.push(String::from("deploy"));
    println!("next up: {next}");
    (next, queue)
}

/// The signature that the compiler's second suggestion and Clippy's
/// `ptr_arg` lint point at together.
pub fn first_word(text: &str) -> &str {
    text.split_whitespace().next().unwrap_or("")
}

/// The corrected caller: it keeps its `String` and lends it.
pub fn first_word_of_owned() -> String {
    let text = String::from("read the error");
    let word = first_word(&text);
    word.to_string()
}

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

    #[test]
    fn the_clone_and_the_borrow_give_the_same_answer() {
        assert_eq!(suggested::report(), "2 lines, the longest is 14 bytes");
        assert_eq!(report(), "2 lines, the longest is 14 bytes");
    }

    #[test]
    fn longest_line_of_nothing_is_zero() {
        assert_eq!(longest_line(&[]), 0);
        assert_eq!(suggested::longest_line(Vec::new()), 0);
    }

    #[test]
    fn the_borrowing_version_leaves_the_vector_with_the_caller() {
        let lines = vec![String::from("a"), String::from("abc")];
        assert_eq!(longest_line(&lines), 3);
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn both_queue_fixes_keep_the_first_job_and_add_the_third() {
        assert_eq!(use_then_push(), ["build", "test", "deploy"]);
        let (next, queue) = copy_then_push();
        assert_eq!(next, "build");
        assert_eq!(queue, ["build", "test", "deploy"]);
    }

    #[test]
    fn first_word_handles_ordinary_and_empty_input() {
        assert_eq!(first_word("read the error"), "read");
        assert_eq!(first_word("  leading space"), "leading");
        assert_eq!(first_word(""), "");
        assert_eq!(first_word("   "), "");
    }

    #[test]
    fn first_word_borrows_from_its_input() {
        let text = String::from("read the error");
        let word = first_word(&text);
        assert!(text.as_bytes().as_ptr_range().contains(&word.as_ptr()));
    }

    #[test]
    fn a_caller_can_lend_its_own_string() {
        assert_eq!(first_word_of_owned(), "read");
    }
}

Tests

$ cargo test --lib compiler_errors::
    Finished `test` profile [unoptimized + debuginfo] target(s)
     Running unittests src/lib.rs (target/debug/build/article-examples/HASH/out/article_examples-HASH)

running 7 tests
test compiler_errors::tests::a_caller_can_lend_its_own_string ... ok
test compiler_errors::tests::both_queue_fixes_keep_the_first_job_and_add_the_third ... ok
test compiler_errors::tests::first_word_borrows_from_its_input ... ok
test compiler_errors::tests::first_word_handles_ordinary_and_empty_input ... ok
test compiler_errors::tests::longest_line_of_nothing_is_zero ... ok
test compiler_errors::tests::the_borrowing_version_leaves_the_vector_with_the_caller ... ok
test compiler_errors::tests::the_clone_and_the_borrow_give_the_same_answer ... ok

test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured

Opt-in lints

With the whole pedantic group and the unwrap_used and expect_used lints switched on, Clippy flags:

  • clippy::needless_pass_by_value on compiler_errors::suggested::longest_line

clippy::needless_pass_by_value, in the pedantic group, flags suggested::longest_line, the version that follows the compiler’s .clone() suggestion: the function still owns a vector it only reads. Nothing flags the fixed versions.

The examples that fail to compile are not in this crate, because it must build; the article shows them and their errors as text. The tests check that the cloning and borrowing versions of longest_line give the same answer, that both fixes for the queue keep the first job and add the third, that first_word returns a slice of its own input, and what it returns for empty and whitespace-only text.

Option is not a nullable: sentinels, defaults and missing data

The article says that every example compiles without warnings, and that Clippy’s default lints say nothing about any of them.

Code

src/option_defaults.rs:

//! The examples from "Option is not a nullable: sentinels, defaults and
//! missing data".

/// The "before" examples: absence replaced by an invented value, or modelled
/// with several `Option`s that must agree.
pub mod before {
    pub fn find_index(names: &[&str], wanted: &str) -> i32 {
        for (i, name) in names.iter().enumerate() {
            if *name == wanted {
                return i as i32;
            }
        }
        -1
    }

    pub struct Customer {
        pub name: String,
        pub email: String, // empty if we have no address
    }

    pub fn reminder_recipients(customers: &[Customer]) -> Vec<&str> {
        customers.iter().map(|c| c.email.as_str()).collect()
    }

    pub fn coldest(readings: &[i32]) -> i32 {
        readings.iter().copied().min().unwrap_or_default()
    }

    pub struct Profile {
        pub nickname: Option<String>,
    }

    impl Profile {
        pub fn apply(&mut self, nickname: Option<Option<String>>) {
            if let Some(change) = nickname {
                self.nickname = change;
            }
        }
    }

    pub struct Delivery {
        pub dispatched_at: Option<u64>,
        pub delivered_at: Option<u64>,
        pub tracking_number: Option<String>,
        pub failure_reason: Option<String>,
    }
}

/// The "after" examples: absence kept in the types, and decided by the code
/// that knows what it means.
pub mod after {
    pub fn find_index(names: &[&str], wanted: &str) -> Option<usize> {
        names.iter().position(|name| *name == wanted)
    }

    pub struct Customer {
        pub name: String,
        pub email: Option<String>,
    }

    pub fn reminder_recipients(customers: &[Customer]) -> Vec<&str> {
        customers
            .iter()
            .filter_map(|c| c.email.as_deref())
            .collect()
    }

    pub fn coldest(readings: &[i32]) -> Option<i32> {
        readings.iter().copied().min()
    }

    pub fn describe(readings: &[i32]) -> String {
        match coldest(readings) {
            Some(celsius) => format!("coldest: {celsius} °C"),
            None => "no readings".to_string(),
        }
    }

    pub struct Profile {
        pub nickname: Option<String>,
    }

    pub enum Change<T> {
        Keep,
        Clear,
        Set(T),
    }

    impl Profile {
        pub fn apply(&mut self, nickname: Change<String>) {
            match nickname {
                Change::Keep => {}
                Change::Clear => self.nickname = None,
                Change::Set(name) => self.nickname = Some(name),
            }
        }
    }

    pub enum Delivery {
        Pending,
        Dispatched {
            at: u64,
            tracking: String,
        },
        Delivered {
            dispatched_at: u64,
            delivered_at: u64,
            tracking: String,
        },
        Failed {
            reason: String,
        },
    }

    impl Delivery {
        pub fn tracking(&self) -> Option<&str> {
            match self {
                Delivery::Dispatched { tracking, .. } | Delivery::Delivered { tracking, .. } => {
                    Some(tracking)
                }
                Delivery::Pending | Delivery::Failed { .. } => None,
            }
        }
    }
}

/// Defaults that are true: a documented contract, and a question whose answer
/// is the same for "not asked" and "refused".
pub mod defaults {
    pub const DEFAULT_RETRIES: u32 = 3;

    pub fn retries(configured: Option<u32>) -> u32 {
        configured.unwrap_or(DEFAULT_RETRIES)
    }

    pub fn may_email(opted_in: Option<bool>) -> bool {
        opted_in.unwrap_or(false)
    }

    pub fn should_ask(opted_in: Option<bool>) -> bool {
        opted_in.is_none()
    }
}

#[cfg(test)]
mod tests {
    use super::{after, before, defaults};
    use std::mem::size_of;
    use std::num::NonZeroU32;

    #[test]
    fn the_sentinel_find_index_returns_minus_one_when_missing() {
        let names = ["Ada", "Grace"];
        assert_eq!(before::find_index(&names, "Grace"), 1);
        assert_eq!(before::find_index(&names, "Linus"), -1);
    }

    #[test]
    fn the_option_find_index_returns_none_when_missing() {
        let names = ["Ada", "Grace"];
        assert_eq!(after::find_index(&names, "Grace"), Some(1));
        assert_eq!(after::find_index(&names, "Linus"), None);
    }

    /// `as` between integer types never fails: it truncates. An index of 2^32
    /// would come back from the sentinel version as 0.
    #[cfg(target_pointer_width = "64")]
    #[test]
    fn a_usize_to_i32_cast_truncates_silently() {
        let index: usize = 1 << 32;
        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        let cast = index as i32;
        assert_eq!(cast, 0);
    }

    #[test]
    fn the_empty_string_sentinel_reaches_the_recipient_list() {
        let customers = [
            before::Customer {
                name: "Ada".to_string(),
                email: "ada@example.com".to_string(),
            },
            before::Customer {
                name: "Grace".to_string(),
                email: String::new(),
            },
        ];
        assert_eq!(customers[1].name, "Grace");
        assert_eq!(
            before::reminder_recipients(&customers),
            ["ada@example.com", ""]
        );
    }

    #[test]
    fn an_optional_email_leaves_customers_without_one_out() {
        let customers = [
            after::Customer {
                name: "Ada".to_string(),
                email: Some("ada@example.com".to_string()),
            },
            after::Customer {
                name: "Grace".to_string(),
                email: None,
            },
        ];
        assert_eq!(customers[1].name, "Grace");
        assert_eq!(after::reminder_recipients(&customers), ["ada@example.com"]);
    }

    #[test]
    fn the_defaulted_coldest_cannot_tell_no_readings_from_freezing() {
        assert_eq!(before::coldest(&[]), 0);
        assert_eq!(before::coldest(&[]), before::coldest(&[0]));
        assert_eq!(before::coldest(&[3, -2, 5]), -2);
    }

    #[test]
    fn the_option_coldest_can() {
        assert_eq!(after::coldest(&[]), None);
        assert_eq!(after::coldest(&[0]), Some(0));
        assert_eq!(after::describe(&[]), "no readings");
        assert_eq!(after::describe(&[3, -2, 5]), "coldest: -2 °C");
    }

    fn default_for_missing<T: Default>(value: Option<T>) -> T {
        value.unwrap_or_default()
    }

    #[test]
    fn unwrap_or_default_uses_the_types_default() {
        assert_eq!(default_for_missing::<i32>(None), 0);
        assert_eq!(default_for_missing::<String>(None), "");
        assert!(!default_for_missing::<bool>(None));
        assert_eq!(default_for_missing::<Vec<u8>>(None), Vec::<u8>::new());
    }

    #[test]
    fn summing_nothing_is_zero_and_the_minimum_of_nothing_is_none() {
        let empty: [i32; 0] = [];
        assert_eq!(empty.iter().sum::<i32>(), 0);
        assert_eq!(empty.iter().min(), None);
        assert_eq!(empty.iter().max(), None);
    }

    #[test]
    fn a_documented_default_applies_only_when_nothing_is_configured() {
        assert_eq!(defaults::retries(None), defaults::DEFAULT_RETRIES);
        assert_eq!(defaults::retries(Some(5)), 5);
        assert_eq!(defaults::retries(Some(0)), 0);
    }

    #[test]
    fn not_asked_and_refused_agree_on_email_but_not_on_asking() {
        assert!(!defaults::may_email(None));
        assert!(!defaults::may_email(Some(false)));
        assert!(defaults::may_email(Some(true)));

        assert!(defaults::should_ask(None));
        assert!(!defaults::should_ask(Some(false)));
        assert!(!defaults::should_ask(Some(true)));
    }

    #[test]
    fn the_nested_option_patch_keeps_clears_and_sets() {
        let mut profile = before::Profile {
            nickname: Some("Ada".to_string()),
        };
        profile.apply(None);
        assert_eq!(profile.nickname.as_deref(), Some("Ada"));
        profile.apply(Some(Some("Countess".to_string())));
        assert_eq!(profile.nickname.as_deref(), Some("Countess"));
        profile.apply(Some(None));
        assert_eq!(profile.nickname, None);
    }

    #[test]
    fn the_change_enum_patch_does_the_same() {
        let mut profile = after::Profile {
            nickname: Some("Ada".to_string()),
        };
        profile.apply(after::Change::Keep);
        assert_eq!(profile.nickname.as_deref(), Some("Ada"));
        profile.apply(after::Change::Set("Countess".to_string()));
        assert_eq!(profile.nickname.as_deref(), Some("Countess"));
        profile.apply(after::Change::Clear);
        assert_eq!(profile.nickname, None);
    }

    #[test]
    fn flatten_merges_both_kinds_of_absence() {
        assert_eq!(None::<Option<u8>>.flatten(), None);
        assert_eq!(Some(None::<u8>).flatten(), None);
        assert_eq!(Some(Some(7_u8)).flatten(), Some(7));
    }

    #[test]
    fn constructing_an_empty_vec_reserves_no_capacity() {
        assert_eq!(Vec::<String>::new().capacity(), 0);
    }

    #[test]
    fn several_options_can_describe_a_delivery_that_never_happened() {
        // Delivered, but never dispatched: the struct accepts it.
        let delivery = before::Delivery {
            dispatched_at: None,
            delivered_at: Some(1_700_000_000),
            tracking_number: None,
            failure_reason: Some("address not found".to_string()),
        };
        assert!(delivery.dispatched_at.is_none() && delivery.delivered_at.is_some());
        assert!(delivery.tracking_number.is_none() && delivery.failure_reason.is_some());
    }

    #[test]
    fn the_delivery_enum_has_a_tracking_number_only_once_dispatched() {
        let pending = after::Delivery::Pending;
        let dispatched = after::Delivery::Dispatched {
            at: 1_700_000_000,
            tracking: "TN123".to_string(),
        };
        let delivered = after::Delivery::Delivered {
            dispatched_at: 1_700_000_000,
            delivered_at: 1_700_086_400,
            tracking: "TN123".to_string(),
        };
        let failed = after::Delivery::Failed {
            reason: "address not found".to_string(),
        };
        assert_eq!(pending.tracking(), None);
        assert_eq!(dispatched.tracking(), Some("TN123"));
        assert_eq!(delivered.tracking(), Some("TN123"));
        assert_eq!(failed.tracking(), None);
    }

    #[test]
    fn option_of_a_plain_integer_needs_extra_space() {
        // Every bit pattern of a usize is a valid number, so None needs room
        // of its own.
        assert!(size_of::<Option<usize>>() > size_of::<usize>());
    }

    #[test]
    fn option_of_a_reference_box_or_nonzero_costs_nothing() {
        // Guaranteed by the standard library (the `option` module's
        // "Representation" section).
        assert_eq!(size_of::<Option<&u8>>(), size_of::<&u8>());
        assert_eq!(size_of::<Option<Box<u8>>>(), size_of::<Box<u8>>());
        assert_eq!(size_of::<Option<NonZeroU32>>(), size_of::<NonZeroU32>());
    }

    #[test]
    fn option_of_a_string_costs_nothing_on_this_compiler() {
        // An observation, not a guarantee: the standard library does not
        // promise this layout for `String`.
        assert_eq!(size_of::<Option<String>>(), size_of::<String>());
    }
}

Tests

$ cargo test --lib option_defaults::
    Finished `test` profile [unoptimized + debuginfo] target(s)
     Running unittests src/lib.rs (target/debug/build/article-examples/HASH/out/article_examples-HASH)

running 20 tests
test option_defaults::tests::a_documented_default_applies_only_when_nothing_is_configured ... ok
test option_defaults::tests::a_usize_to_i32_cast_truncates_silently ... ok
test option_defaults::tests::an_optional_email_leaves_customers_without_one_out ... ok
test option_defaults::tests::constructing_an_empty_vec_reserves_no_capacity ... ok
test option_defaults::tests::flatten_merges_both_kinds_of_absence ... ok
test option_defaults::tests::not_asked_and_refused_agree_on_email_but_not_on_asking ... ok
test option_defaults::tests::option_of_a_plain_integer_needs_extra_space ... ok
test option_defaults::tests::option_of_a_reference_box_or_nonzero_costs_nothing ... ok
test option_defaults::tests::option_of_a_string_costs_nothing_on_this_compiler ... ok
test option_defaults::tests::several_options_can_describe_a_delivery_that_never_happened ... ok
test option_defaults::tests::summing_nothing_is_zero_and_the_minimum_of_nothing_is_none ... ok
test option_defaults::tests::the_change_enum_patch_does_the_same ... ok
test option_defaults::tests::the_defaulted_coldest_cannot_tell_no_readings_from_freezing ... ok
test option_defaults::tests::the_delivery_enum_has_a_tracking_number_only_once_dispatched ... ok
test option_defaults::tests::the_empty_string_sentinel_reaches_the_recipient_list ... ok
test option_defaults::tests::the_nested_option_patch_keeps_clears_and_sets ... ok
test option_defaults::tests::the_option_coldest_can ... ok
test option_defaults::tests::the_option_find_index_returns_none_when_missing ... ok
test option_defaults::tests::the_sentinel_find_index_returns_minus_one_when_missing ... ok
test option_defaults::tests::unwrap_or_default_uses_the_types_default ... ok

test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured

Opt-in lints

With the whole pedantic group and the unwrap_used and expect_used lints switched on, Clippy flags:

  • clippy::cast_possible_truncation on option_defaults::before::find_index
  • clippy::cast_possible_wrap on option_defaults::before::find_index

clippy::cast_possible_truncation and clippy::cast_possible_wrap, in the pedantic group, flag the i as i32 in the “before” find_index: they object to the cast the sentinel needs, not to the -1 itself. clippy::option_option, also in pedantic, stays silent on the Option<Option<String>> in the “before” Profile::apply, because Clippy’s avoid-breaking-exported-api setting (on by default) exempts public items.

Nothing flags the 0 °C that unwrap_or_default() invents in the “before” coldest, the empty string standing in for a missing email address, or a Delivery that was delivered without being dispatched. The tests check that the “before” coldest returns the same answer for no readings as for a reading of zero, that the empty email reaches the recipient list, that both versions of apply keep, clear and set a nickname alike, and that the contradictory Delivery can be built. Of the size tests, the one for references, Box and NonZeroU32 checks a documented guarantee; the one for Option<String> is an observation of this compiler, not a promise.