Module 9 · Lesson 109 of 112

The written exam and the practical

Explain the written assessment, build a timed concurrent Rust program, and repair a review sample with ownership, error handling, and memory safety defects.

  • Beginner to advanced
  • 10 min read
  • 70 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with Rust, Cargo, and Clippy; no board required

Your place in the module
By the end you can 4 objectives
  • Answer written questions across the module's Rust and systems topics with concrete reasoning.
  • Build a concurrent sensor publisher that meets its input, output, and failure contract.
  • Repair a borrow conflict, a dangling pointer, a data race, and a swallowed I/O error.
  • Record written and code-review practice scores with evidence against the module checklist.
Video coming soonThe written exam and the practical
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Mock interviews and the gotcha checklist
  • A lifetime annotation describes a relationship between borrows and does not extend the owner's lifetime.
  • A trait object uses dynamic dispatch, and question-mark propagation can convert an error before returning it.
  • Pin constrains movement of the pointee when the type requires pinning, while Send governs transfer between threads.
01

What the written assessment asks

4 min read

The interview prep ended with mock interviews. This lesson answers what the written exam and the timed practical assessment require.

A Linux device reader has to handle a real distinction. At the read(2) boundary, a successful call can transfer fewer bytes than requested, and an error has a separate return convention. That distinction matters when a Rust wrapper turns a C return value into a byte count or an error. A written answer earns credit by preserving the distinction and explaining what makes the translation valid. Recognizing the API name is only the start of the answer. read(2)

Expect prompts that ask you to predict whether a snippet compiles, trace what happens on success and failure, or choose between two designs under a stated constraint. Give the result first, identify the relevant value or operation, and explain the rule that determines the result. For a rejected borrow, identify where the borrow is created, where it is used again, and which mutation conflicts with it. If a prompt asks for a change, show the smallest change that preserves the required behavior and explain what the caller can still do afterward.

  • Ownership, borrowing, and lifetimes. Trace which function or closure owns a value after a move. For a returned reference, name the input or allocation it points into and explain how long that storage remains valid. If two inputs are borrowed and the return value comes from only one, explain which input the return lifetime needs to follow.
  • Traits and generics. Read a signature and connect each bound to something the implementation does. A question might ask which signature supports different implementations chosen at runtime. Explain what a generic parameter gives the caller and where a trait object supplies dynamic dispatch.
  • Error handling. Distinguish an expected absence from an operation that failed. Follow ? through the enclosing function and say which error reaches its caller. If the question involves a command-line program, explain where to add the path or operation name so the diagnostic identifies the failed input.
  • Collections, iterators, and closures. Track the item type through an iterator chain, including whether the items are owned or borrowed. State which operation consumes the iterator and what the closure borrows or moves from its environment. If a collection is still needed later, account for its ownership when selecting an iterator.
  • Smart pointers. Choose based on who owns the value and where it is used. Explain when Box gives one owner, when Rc gives shared ownership within a thread, and when Arc lets threads share ownership. If the contents change, name the separate mechanism that controls access to them.
  • Concurrency and async. Identify who owns the work, who observes completion, and how failures reach that observer. For threads, connect Send or Sync to the value crossing or being shared across a thread boundary. For async, identify which values or guards live across an .await and what happens to unfinished work when a future is dropped.
  • FFI and unsafe. State what the caller must establish before an unsafe operation, including the relevant lifetime, pointer validity, length, and ownership or cleanup rules. When reviewing a wrapper, identify where it establishes those conditions and which conditions depend on the foreign library's contract.
  • Embedded and kernel Rust. Identify whether the example is Linux user space, bare metal, or kernel space. Explain which facilities the environment supplies, such as an allocator or device abstraction, and which context constrains the operation. A kernel build question should tie Rust support to the kernel configuration and build prerequisites. Kernel Rust Quick Start
Evidence in a written answerPredictoutcomeIdentifyaffectedcodeExplaingoverningrulePredictoutcomeIdentifyaffectedcodeExplaingoverningrule
A complete written answer connects the outcome to a rule and the affected code

When a prompt allows several designs, state the assumption that makes yours fit. For example, a scoped worker can borrow paths because the scope waits for its threads to finish before the caller's storage goes away. A worker that must outlive that scope needs a different ownership arrangement. Both answers can be reasonable under different requirements. Naming the requirement gives the reviewer a concrete basis for evaluating your choice.

Write predictions before compiling the practice snippets. After checking them, keep the original answer and record any correction beside it. A compiler diagnostic can confirm that a borrow is rejected. Your explanation should still identify the two uses that make the rejection necessary. Keep the same distinction when a snippet compiles. Compilation answers the type-checking question, and you still owe an answer about its specified runtime behavior.

02

What the timed practical must deliver

3 min read

The practical gives you a small program specification and a time limit. Use the specification to decide what goes into the submission. A concurrent file-watcher brief, for example, would need to say whether it expects filesystem events or periodic snapshots. Linux exposes filesystem events through inotify, and a periodic reader observes the state at the times it reads. That difference affects what a test can require. The practice brief here uses a finite sensor publisher so every run has a defined end. inotify(7)

The publisher takes one or more file paths as positional arguments. Each file represents a sensor sample. Read each as UTF-8 text, trim surrounding whitespace, and parse the remaining text as a Rust u32. Each input gets its own worker. On success, publish the decimal values to standard output, one per line in argument order. A duplicate path produces a reading at each position where it appears. With no paths, report a usage error on standard error and exit unsuccessfully. If any input fails to read or parse, report the first failing path in argument order and the cause on standard error, with unsuccessful exit status and empty standard output. The empty-output requirement applies to input failures, which can be detected before publication starts.

Publishing concurrent readingsStartworkersJoinworkersCheckresultsUseargumentorderPublishreadingsExit from step 3: input failureReport first errorStartworkersJoinworkersCheckresultsUseargumentorderPublishreadingsExit from step 3: inputfailureReport first error
Workers collect readings before the caller decides whether to publish

Workers can return a Result to the caller. With scoped threads, each worker may borrow its path, and the caller can keep the handles in argument order. Spawn the workers before joining them so the reads can overlap. Collect each worker's outcome, including any unexpected panic reported by a join, before returning from the operation. Inspect the outcomes in input order. The worker that finishes first has no special status under the specification. Publishing from the caller after validation also means the workers need no shared mutable output buffer.

Keep the program structure easy to inspect under the time limit. A function that reads and parses one sample can own the temporary text and return only the number or an error. A coordinating function can handle worker results and preserve input order. The command-line entry point can handle arguments, output, and exit status. These can be functions in one crate. Use idiomatic error propagation where the caller can act on a failure, and add context where you know what failed. Handle a publication write error as an output failure. Writes that have already succeeded may be visible if the output stream later fails.

Budget time for a buildable version early and leave time to rerun checks after edits. First establish a successful path from arguments to output. Then verify behavior for missing and malformed files. A useful order test supplies distinct values in a deliberately chosen argument order and asserts the exact lines. For the failure test, a valid input followed by a malformed one checks that successful work done earlier stays unpublished. Supply multiple bad inputs to check that reporting follows argument order. These assertions rely on the contract and work without timing sleeps.

Run cargo test and cargo clippy --all-targets in the crate. Read the test summary and lint diagnostics before submitting. A passing test run covers the cases it actually asserts, while Clippy reports patterns from its configured lints. A reviewer also reads the ownership and error paths. They should be able to see where each value lives, where workers finish, and how a failure reaches the caller. This program can use safe Rust throughout. If a different brief genuinely requires an unsafe operation, its submission needs a justification that names the invariant and shows how the code establishes it.

03

Review defective code and record evidence

4 min read
Going deeperExplore the mechanism

The review exercise uses a separate function with a small contract. Given input paths, return the number of files whose first byte is nonzero. Empty files and files starting with a zero byte contribute zero. A read error must reach the caller with the identity of the first failing input in argument order. Multiple files can be read concurrently, and repeated calls must compute a fresh result from their own inputs.

The following Rust sample is deliberately defective. Review it by inspection. Its borrow conflict prevents this version from compiling, and editing just that conflict would leave undefined behavior in the code.

rust
use std::{fs, io, path::PathBuf, thread};

static mut COUNT: usize = 0;

fn count_files(paths: &[PathBuf]) -> io::Result<usize> {
    thread::scope(|scope| {
        for path in paths {
            scope.spawn(move || {
                let Ok(mut bytes) = fs::read(path) else {
                    return;
                };
                let first = bytes.first();
                let ptr = bytes.as_ptr();
                bytes.clear();
                if first.is_some() {
                    drop(bytes);
                    unsafe {
                        if *ptr != 0 {
                            COUNT += 1;
                        }
                    }
                }
            });
        }
    });
    Ok(unsafe { COUNT })
}

bytes.first() returns an optional shared reference into the vector. The later first.is_some() uses the value containing that borrow, so bytes.clear() conflicts with it. The contract requires inspecting the first byte and gives no reason to clear the vector before that inspection. Use bytes.first().copied() to obtain a byte value while the vector is valid. Compare the result as a value and let the vector drop normally.

The pointer from bytes.as_ptr() is tied to the vector's allocation. On the nonempty branch, drop(bytes) frees that allocation before the dereference. Having seen that the vector was nonempty establishes only that there was a first byte when the vector was live. Replace the entire raw-pointer read with the safe value check. A successful run after a partial edit would provide no assurance about the dangling dereference.

COUNT += 1 reads and writes shared storage with no synchronization. If multiple workers reach the update, those conflicting accesses can constitute a data race. The scope waits for the workers before the final read, but that wait leaves the workers free to overlap with each other. The global also persists across calls. Have each worker return its own contribution and sum the contributions in the caller. This gives each invocation its own total and eliminates the shared writes.

The read failure becomes an early return from a closure that reports no error. Change the worker to return a result that carries either its contribution or a read error. Preserve each result's associated input path so the caller can report it. Join all workers and inspect the outcomes in input order, including a separate error for a worker panic if one occurs. A test with an empty file establishes a valid zero contribution. A test with a missing file establishes that the error reaches the caller. Add a repeated-call test with a nonzero first byte to detect a total that accidentally persists.

Evidence for the review fixesFixEvidenceBorrow conflictCopy firstbyteSuccessfulcompilationDangling pointerUse safeaccessInspect valuelifetimeData raceReturn workerresultsInspect stateownershipLost errorPropagateread errorTest missingfile
Each defect needs a code change and evidence suited to the failure

For practice, keep a record alongside your code. Score the eight written topics above with one point per topic when your answer gives the correct outcome and the rule or constraint that explains it. Mark omissions and unsupported guesses as zero, then write the correction. For the review, record one point per defect when you can name its cause and show the corresponding fix. Record the two totals separately out of eight and four. These are self-check scores for the exercises.

Use the module checklist to record evidence for ownership, justified use of unsafe if present, error handling, tests, and clean structure. Tie each entry to something a reader can inspect. A worker returning a byte classification supports the ownership entry, and a missing-file assertion supports the error-handling entry. For a safe rewrite, point out that the raw pointer and global mutation were removed. Record the Clippy and test results separately and mark any case you did not run as unverified.

The next lesson, “The gates, rubric, and unsafe audit,” explains how the assessment applies its checks to the program, review notes, and verification evidence you submit.

Key takeaways

  • The written assessment asks you to predict behavior and explain the rules behind it.
  • The timed practical is assessed against its specification, Clippy, and tests.
  • Joining workers observes completion, while synchronization or exclusive ownership prevents concurrent conflicting access.
  • A clean build leaves runtime behavior, error reporting, and unsafe invariants to be checked separately.
Reflect
  1. Explain to a colleague, in two sentences: answer written questions across the module's Rust and systems topics with concrete reasoning.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close