Errors, tests and debugging

A Rust program has two ways to fail, and this chapter keeps them apart. A panic stops the thread; a Result is a value the caller handles, and these twelve lessons write both: the panic and its exit code, an error enum of your own, ? through the layers, and the assertions that fail a test. cargo test comes next, with a temporary directory and an injected clock, then gdb on a real panic. The chapter ends at the boundary: the unsafe block and its contract, pointer arithmetic, the memory layout, uninitialised memory, and a C function called across extern "C".

061 panics, unwinding and catch_unwind panic!, the message and the exit code, unwinding, catch_unwind and panic = "abort" (C++ 077, 080) Open 062 Custom error types an enum of errors, Display and Error, From for the layers above, and one error type per module (C++ 079) Open 063 The question mark through layers ? in every layer, Box<dyn Error> at the top, adding context and a non-zero exit code (C++ 078, 081) Open 064 assert!, debug_assert! and unreachable! a checked condition, debug_assert in release, unreachable! and #[must_use] (C++ 082) Open 065 Unit tests with cargo test #[test], assert_eq!, tests beside the code, cargo test output and a first regression (C++ 085) Open 066 Testing files and time a temporary directory per test, an injected clock and a test that does not depend on the wall clock (C++ 086) Open 067 Debugging Rust with gdb rustc -g, break on a Rust function, print a value, backtrace and a panic found in gdb (C++ 083) Open 068 unsafe, raw pointers and undefined behaviour an unsafe block, *const and *mut, dereferencing a raw pointer, and the contract the programmer takes on (C++ 087, 084) Open 069 Pointer arithmetic and ptr::read add and offset, one past the end, ptr::read and ptr::write, and the bug that reads past a buffer (C++ 088) Open 070 size_of, align_of and repr size and alignment, padding in a struct, repr(C) for a defined layout and repr(transparent) (C++ 094) Open 071 MaybeUninit and object lifetime MaybeUninit, assume_init, an explicit drop call and the lifetime rules unsafe code must keep (C++ 095) Open 072 Calling C from Rust extern "C", a C function called from Rust, a Rust function called from C, and the layout the boundary needs (C++ 136) Open

Lessons