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());
}
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, ā¦ā