keyword

Rust safe: mark a safe foreign declaration

Rust 2024 permits explicit safe functions and statics inside unsafe extern blocks. Only declare an item safe when its Rust-facing contract has no extra caller safety obligations. This example declares POSIX getpid, which takes no arguments. Expected output (not executed): true Why: On the specified Linux x86-64 target, getpid returns the positive process ID; no exact PID is assumed. Common mistake: The safe marker does not prove that the signature or implementation is correct. Never use it to hide a caller safety obligation. Target requirement: x86_64-unknown-linux-gnu with libc; do not run on arbitrary targets.

Formal Syntax & Structure

rust syntaxrust
unsafe extern "C" { safe fn name(); }

Working Example

Example Snippetrust
unsafe extern "C" {    // SAFETY: POSIX getpid takes no arguments, returns pid_t (i32 on this target),    // and has no extra caller preconditions.    safe fn getpid() -> i32;}
fn main() {    println!("{}", getpid() > 0);}
Rust Reference