Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Determining Preconditions

Where do you find the safety preconditions?

// Copyright 2026 Google LLC
// SPDX-License-Identifier: Apache-2.0

fn main() {
    let b: *mut i32 = std::ptr::null_mut();
    println!("{:?}", b.as_mut());
}
This slide and its sub-slides should take about 10 minutes.

Attempt to compile the program to trigger the compiler error (ā€œerror[E0133]: call to unsafe function ā€¦ā€).

Ask: ā€œWhere would you look if you wanted to know the preconditions for a function? Here we need to understand when it’s safe to convert from a null pointer to a mutable reference.ā€

Locations to look:

  • A function’s API documentation, especially its safety section
  • The source code and its internal safety comments
  • Module documentation
  • Rust Reference

Consult the documentation for the as_mut method.

Highlight Safety section.

Safety

When calling this method, you have to ensure that either the pointer is null or the pointer is convertible to a reference.

Click the ā€œconvertible to a referenceā€ hyperlink to the ā€œPointer to reference conversionā€

Track down the rules for converting a pointer to a reference, i.e., whether it is ā€œdereferenceableā€.

Consider the implications of this excerpt (Rust 1.90.0) ā€œYou must enforce Rust’s aliasing rules. The exact aliasing rules are not decided yet, ā€¦ā€