Skip to content
systemcoding.dev
Systems Programming

The Complete Guide to Systems Programming in Rust on Linux

Write Linux systems code in Rust with compile-time ownership checks, safe syscall wrappers, and the exact boundary where unsafe remains necessary.

28 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Rust, Linux and C logos.

Rust's pitch for systems programming is specific and checkable: the compiler enforces, at compile time, properties that C and C++ leave to discipline and review, no use-after-free, no data race on shared memory, no null-pointer dereference through a safe reference. None of this makes a syscall behave differently; open() still returns a file descriptor or an error exactly as it does from C. What changes is how much of the surrounding bookkeeping the compiler verifies rather than trusts. This guide covers systems programming in Rust 1.84 on Linux, and like the companion guides to C and modern C++ on this site, it is explicit throughout about where Rust's guarantees stop and unsafe code, with all of C's old hazards, begins again.

The borrow checker's actual job

Rust's ownership model assigns every value exactly one owner at a time, and the borrow checker verifies, at compile time, that a reference to a value never outlives the value itself and that a value is never mutated through one reference while another reference is reading it. This is the same shape of bug the C++ companion guide's std::span section describes as unsolved by that abstraction alone, a dangling or conflicting reference, except Rust's compiler actually rejects the code rather than merely making the mistake harder to write by accident.

ownership_demo.rsrust
fn main() {
    let data = vec![1, 2, 3];
    let reference = &data;

    println!("{:?}", reference);
    // data is still valid here; the borrow in `reference` ended at last use
}
Text
$ rustc -O ownership_demo.rs -o ownership_demo
$ ./ownership_demo
[1, 2, 3]

A version of this code that tried to free data while reference was still in scope and later used would not compile at all; the error points at the exact line where the conflict occurs, with the compiler explaining which borrow conflicts with which, rather than a C++ program compiling cleanly and producing undefined behavior only at runtime, intermittently, under the specific conditions that happen to trigger it.

Safe wrappers over raw syscalls through std::fs and std::os

Most Linux-facing Rust code never calls a raw syscall directly; std::fs, std::net and std::process wrap the common operations in safe, idiomatic APIs that return Result rather than a sentinel value, and the standard library itself handles resource cleanup through Rust's Drop trait, the direct analog of C++'s RAII destructor.

fs_open.rsrust
use std::fs::File;
use std::io::Read;

fn main() -> std::io::Result<()> {
    let mut file = File::open("/etc/hostname")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    println!("read: {}", contents.trim());
    Ok(())
}
Text
$ rustc -O fs_open.rs -o fs_open
$ ./fs_open
read: myhost

The ? operator propagates an Err immediately, returning it from the current function rather than continuing, which is Rust's idiomatic alternative to exceptions: every fallible call's result must be explicitly handled, assigned, or propagated with ?, and the compiler rejects a program that silently discards a Result without acknowledging it, through a #[must_use] lint the standard library applies to Result itself. File's underlying file descriptor closes automatically when file goes out of scope, through its Drop implementation, with the same unconditional, every-exit-path guarantee RAII provides in C++, including on an early return via ? partway through the function.

Reaching below std for a raw syscall with libc

When the standard library's abstraction does not cover a specific Linux-only syscall, the libc crate provides raw FFI bindings to the C library, and calling one of them is unsafe, because the compiler cannot verify a raw syscall's own safety contract the way it verifies ordinary Rust code.

raw_syscall.rsrust
use std::ffi::CString;

fn main() {
    let path = CString::new("/etc/hostname").unwrap();
    let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY) };

    if fd == -1 {
        let err = std::io::Error::last_os_error();
        eprintln!("open failed: {}", err);
        return;
    }

    println!("opened fd: {}", fd);
    unsafe { libc::close(fd) };
}
Text
$ cat > Cargo.toml <<'EOF'
[package]
name = "raw_syscall"
version = "0.1.0"
edition = "2021"
[dependencies]
libc = "0.2"
EOF
$ cargo run --release
opened fd: 3

The unsafe block around libc::open is not a blanket disabling of Rust's checks; it specifically marks the one operation the compiler cannot itself verify (that the raw pointer passed to open is valid and null-terminated for the syscall's lifetime), and everything else in the function, the CString construction, the error check, the println!, remains fully checked, ordinary safe Rust. This is the Rust equivalent of the C ABI boundary the companion C++ guide describes: unsafe marks exactly where the compiler's guarantees stop, nothing more and nothing less.

Concurrency: Send, Sync, and what they actually check

Rust's two marker traits for thread safety, Send (a type safe to move to another thread) and Sync (a type safe to share, by reference, across threads), are not conventions a programmer has to remember to apply correctly; the compiler derives them automatically for most types based on their fields, and a type containing something genuinely unsafe to share, a raw pointer with no further guarantee, for instance, is automatically neither Send nor Sync unless a programmer explicitly, and in an unsafe impl block, asserts otherwise, taking on the responsibility of proving that assertion correct themselves.

thread_safety.rsrust
use std::thread;
use std::sync::{Arc, Mutex};

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..4 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("final count: {}", *counter.lock().unwrap());
}
Text
$ rustc -O thread_safety.rs -o thread_safety
$ ./thread_safety
final count: 4

Arc<Mutex<i32>> is checked at compile time, not merely by convention, to be the only way this shared counter can cross the thread boundary safely: a plain, unprotected i32 shared by reference across the thread::spawn calls would fail to compile, because the compiler can see that a bare &i32 shared mutably across threads with no synchronization violates Sync's own contract, catching the data race at compile time rather than leaving it to a tool like ThreadSanitizer to discover at runtime, which is precisely the gap the companion C++ guide names as unclosed by RAII and lock guards alone.

Where unsafe remains genuinely necessary

Four categories of Linux systems code cannot be expressed in safe Rust at all, and reach for unsafe as a matter of necessity rather than convenience: raw pointer dereferencing for FFI with C libraries, direct memory-mapped I/O (mmap's result is fundamentally a raw pointer the compiler cannot track ownership of the way it tracks a Box or a Vec), inline assembly for architecture-specific operations, and implementing a custom unsafe trait like Send for a type the compiler cannot automatically verify is safe to share.

unsafe_mmap.rsrust
use std::fs::File;
use std::os::unix::io::AsRawFd;

fn main() -> std::io::Result<()> {
    let file = File::open("/etc/hostname")?;
    let len = file.metadata()?.len() as usize;

    let ptr = unsafe {
        libc::mmap(
            std::ptr::null_mut(),
            len,
            libc::PROT_READ,
            libc::MAP_PRIVATE,
            file.as_raw_fd(),
            0,
        )
    };

    if ptr == libc::MAP_FAILED {
        return Err(std::io::Error::last_os_error());
    }

    let slice = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) };
    println!("mapped {} bytes, first byte: {}", len, slice[0]);

    unsafe { libc::munmap(ptr, len) };
    Ok(())
}
Text
$ cargo run --release
mapped 9 bytes, first byte: 109

std::slice::from_raw_parts is itself unsafe because the function has no way to verify that the pointer and length it is given actually describe valid, readable memory for the slice's entire claimed lifetime; the programmer is asserting that invariant by calling it, exactly the same shape of responsibility C++'s reinterpret_cast or a raw mmap call places on the programmer, except Rust forces that specific assertion to be marked, textually, with the unsafe keyword, making every such assertion in a codebase individually greppable and reviewable in a way C and C++ code offers no equivalent for.

Lifetimes made explicit: when the compiler needs help

The borrow checker's analysis in the earlier example worked without any annotation because the relationship between data and reference was simple enough for the compiler to infer entirely on its own, a capability called lifetime elision. A function returning a reference derived from one of several input references needs an explicit lifetime annotation, because the compiler cannot always infer which input the output reference's validity is actually tied to without being told.

explicit_lifetime.rsrust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

fn main() {
    let s1 = String::from("short");
    let result;
    {
        let s2 = String::from("a longer string");
        result = longest(s1.as_str(), s2.as_str());
        println!("longest: {}", result);
        // result must not be used after this point, since s2 is about to end
    }
}
Text
$ rustc -O explicit_lifetime.rs -o explicit_lifetime
$ ./explicit_lifetime
longest: a longer string

The 'a annotation here is not creating a new rule; it is making an existing one, that the returned reference's validity is tied to the shorter-lived of the two inputs, explicit enough for the compiler to check it mechanically. Moving the println! outside the inner block, where s2 has already gone out of scope, produces a compile error naming exactly which borrow has outlived its owner, which is the direct, textual equivalent of the use-after-free bug the companion C++ guide's std::span section describes as a gap no amount of span usage closes on its own; in Rust, the identical mistake is a compile-time rejection rather than a runtime hazard waiting to be triggered.

Interior mutability: Cell, RefCell, and when borrowing rules are checked at runtime instead

Rust's default aliasing rule, at most one mutable reference or any number of immutable ones, at compile time, is sometimes too restrictive for a genuinely safe pattern the compiler cannot prove safe through static analysis alone, a node in a graph structure that needs to be mutated through a shared reference held by multiple other nodes, for instance. RefCell<T> moves that check from compile time to runtime: it allows mutation through a shared reference, but panics immediately if the actual runtime borrowing pattern would have violated the rule the compiler normally enforces statically.

refcell_demo.rsrust
use std::cell::RefCell;

fn main() {
    let shared = RefCell::new(vec![1, 2, 3]);

    {
        let mut borrowed = shared.borrow_mut();
        borrowed.push(4);
    } // the mutable borrow ends here, checked at runtime

    println!("{:?}", shared.borrow());
}
Text
$ rustc -O refcell_demo.rs -o refcell_demo
$ ./refcell_demo
[1, 2, 3, 4]

Attempting to call shared.borrow_mut() a second time while the first mutable borrow from the inner block was still alive, rather than letting it end at the closing brace as shown, would compile successfully (since RefCell defers the check) but panic at runtime with "already borrowed: BorrowMutError", which is a deliberate, documented trade: RefCell moves the enforcement point later, to a point where a genuine violation is still caught, just not as early as the default, fully static borrow-checker analysis catches it. Reach for it specifically when a data structure's shape genuinely needs shared mutability the compiler cannot verify statically, not as a general workaround for a borrow-checker error that a different data structure or ownership pattern would resolve more cleanly.

Zero-cost abstractions and iterator chains

Rust's iterator combinators, map, filter, fold and similar, are frequently cited as a "zero-cost abstraction" in the same sense the companion C++ guide's syscall-wrapper post applies to a thin, inlined wrapper function: a chain of iterator calls compiles, after optimization, to code indistinguishable from a hand-written loop performing the same work, with no per-element function-call overhead or heap allocation introduced by the abstraction itself.

iterator_chain.rsrust
fn main() {
    let numbers: Vec<i32> = (1..=20).collect();

    let sum_of_even_squares: i32 = numbers
        .iter()
        .filter(|&&n| n % 2 == 0)
        .map(|&n| n * n)
        .sum();

    println!("sum of even squares: {}", sum_of_even_squares);
}
Text
$ rustc -O iterator_chain.rs -o iterator_chain
$ ./iterator_chain
sum of even squares: 1540

Compiled at -O (equivalent to cargo build --release's optimization level), this chain of filter, map and sum calls typically compiles down to a single tight loop with no intermediate allocation for each stage, a result verifiable the same way the companion C++ guide verifies its zero-overhead syscall wrapper claim, by inspecting the generated assembly directly with cargo asm or objdump rather than trusting the claim on faith; LLVM, the backend both rustc and Clang share, performs this inlining and loop-fusion optimization the same way across both languages, which is part of why the claim transfers as directly as it does.

Testing systems-level Rust

Rust's built-in test framework, invoked with cargo test, needs no separate testing library for ordinary unit and integration tests, which is a meaningfully lower-friction starting point than C++'s reliance on a third-party framework like Google Test or Catch2 for the same job.

tested_lib.rsrust
pub fn parse_port(input: &str) -> Result<u16, std::num::ParseIntError> {
    input.trim().parse::<u16>()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_valid_port() {
        assert_eq!(parse_port("8080"), Ok(8080));
    }

    #[test]
    fn rejects_out_of_range_port() {
        assert!(parse_port("99999").is_err());
    }
}
Text
$ cargo test
running 2 tests
test tests::parses_valid_port ... ok
test tests::rejects_out_of_range_port ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Beyond cargo test, Miri, an interpreter for Rust's mid-level intermediate representation distributed as a rustup component (rustup component add miri), specifically detects undefined behavior inside unsafe blocks that ordinary compilation and testing would miss entirely, a misaligned pointer access, a read of uninitialized memory, the exact category of bug the companion C and C++ guides on this site rely on AddressSanitizer and UndefinedBehaviorSanitizer to catch. Running cargo miri test on any codebase containing unsafe code, particularly the raw syscall and mmap examples earlier in this guide, is worth treating as a standing part of the test suite rather than a one-off check, exactly the same recommendation the companion C++ guide makes for sanitizers there.

Interfacing Rust and C in both directions

The libc-based examples earlier in this guide call from Rust into C; the reverse direction, exposing a Rust function for C code to call, needs the same extern "C" linkage marker C++'s own FFI boundary uses, which the companion C++ guide's section on the C ABI covers from the other side of the same boundary.

rust_from_c.rsrust
#[no_mangle]
pub extern "C" fn add_two_numbers(a: i32, b: i32) -> i32 {
    a + b
}

#[no_mangle] disables Rust's own name-mangling scheme for this function specifically, so the symbol a C linker sees matches the plain name add_two_numbers rather than a mangled, Rust-specific internal name, exactly mirroring what extern "C" accomplishes for a C++ function crossing the same boundary in the other direction. A C program linking against a shared library built from this Rust code calls add_two_numbers exactly as it would call a C function with the same signature, with neither side needing to know or care which language actually implemented it, which is the entire point of a shared, stable ABI: it is the common language two otherwise-incompatible compilation models agree to speak at the boundary.

Building and the Cargo toolchain

Cargo is Rust's combined build system and package manager, and most Linux systems code depends on at least the libc crate for raw FFI access, declared in Cargo.toml and resolved automatically on the first build.

Text
$ cargo new my_systems_tool
$ cd my_systems_tool
$ cargo build --release
   Compiling my_systems_tool v0.1.0
    Finished release [optimized] target(s) in 0.42s

--release enables optimizations comparable to GCC's -O2/-O3; a debug build (the default with plain cargo build) includes overflow checks and debug assertions that a release build strips for performance, which matters for systems code specifically because an unchecked integer overflow in a release build wraps silently (matching C's own historical behavior for unsigned types, and, since a 2021 stabilization, Rust's own well-defined two's-complement wrapping semantics for both signed and unsigned integers when explicitly requested), while a debug build panics loudly on the same overflow, a difference worth testing against deliberately rather than discovering only once code that passed every debug-build test behaves differently once shipped in release mode.

Error handling: Result, panic, and process::exit

Rust draws a line similar to the one the companion C++ guide draws between exceptions and error codes, but with different named mechanisms. Result<T, E>, propagated with ?, is the default for any operation that can fail in an expected, routine way, a missing file, a parse error, exactly the role std::expected plays in modern C++. panic! unwinds the stack (by default) and is reserved for a logic error that indicates a bug, an index genuinely out of bounds, an invariant violated, rather than an expected failure mode; a panic in Rust is closer in spirit to an assertion failure than to an exception meant to be caught and handled as part of normal control flow, though std::panic::catch_unwind does exist for the narrower cases (embedding Rust inside a host that cannot tolerate an unwind crossing its own boundary, notably) where catching one is genuinely necessary.

error_handling.rsrust
use std::fs;

fn read_config(path: &str) -> Result<String, std::io::Error> {
    fs::read_to_string(path)
}

fn main() {
    match read_config("/etc/myapp/config.json") {
        Ok(content) => println!("loaded {} bytes", content.len()),
        Err(e) => {
            eprintln!("fatal: could not read config: {}", e);
            std::process::exit(1);
        }
    }
}
Text
$ rustc -O error_handling.rs -o error_handling
$ ./error_handling
fatal: could not read config: No such file or directory (os error 2)

std::process::exit(1) here plays the role a fatal, uncaught C++ exception would play in the companion guide's own layered error-handling design, a deliberate, explicit decision that this particular failure cannot be recovered from, made at the specific point an application layer determines that, rather than letting the error silently propagate further than intended.

Async I/O with Tokio: a different event-loop model than epoll in C++

The companion C++ guide builds a coroutine-based epoll wrapper by hand, as a teaching example of the underlying mechanism. Production async networking code in Rust almost never does the equivalent by hand; the ecosystem has converged heavily on Tokio, a batteries-included async runtime that wraps epoll (or io_uring through a separate, newer runtime option) behind async/await, Rust's own native syntax for suspending and resuming a function at well-defined points, directly analogous to C++20's co_await but integrated into the language's type system from the start rather than requiring a hand-built coroutine type and promise protocol the way the C++ example needed.

tokio_echo.rsrust
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;
    println!("listening on 127.0.0.1:8080");

    loop {
        let (mut socket, _) = listener.accept().await?;
        tokio::spawn(async move {
            let mut buf = [0u8; 1024];
            loop {
                match socket.read(&mut buf).await {
                    Ok(0) => break, // connection closed
                    Ok(n) => {
                        if socket.write_all(&buf[..n]).await.is_err() {
                            break;
                        }
                    }
                    Err(_) => break,
                }
            }
        });
    }
}
Text
$ cargo run --release
listening on 127.0.0.1:8080

#[tokio::main] is a macro that wraps the whole main function in Tokio's own runtime setup, the equivalent of the manually-written EpollLoop::run_once() dispatch loop in the companion C++ guide's coroutine example, but with the scheduler, task spawning (tokio::spawn), and the readiness-polling machinery all implemented and tested by the Tokio project rather than hand-rolled per application. Each tokio::spawn-ed task is conceptually similar to the per-connection coroutine the C++ example spawns for each accepted client, suspended at each .await point and resumed when its underlying socket operation completes, with the scheduler multiplexing many such tasks over a small number of OS threads, typically matching the CPU core count by default.

Why Rust's standard library chose not to include an async runtime

Unlike std::fs and std::net's synchronous APIs, Rust's standard library deliberately ships no async runtime of its own, leaving async/await as a language feature with multiple, interchangeable runtime implementations (Tokio being the dominant one, with async-std and smol as lighter alternatives) rather than one blessed, standard choice the way Node.js or Go bundle a single runtime into the language itself. This is a considered trade-off rather than an oversight: a systems program with no networking at all pays zero binary-size or dependency cost for async machinery it never uses, and a specialized embedded or kernel-adjacent context can select a runtime, or write a minimal one, tuned to its own specific constraints rather than being stuck with a one-size-fits-all default baked into the language. The cost is that two Rust libraries built against different async runtimes do not always compose cleanly without an adapter layer, a genuine, occasionally frustrating fragmentation point the ecosystem has partially converged away from as Tokio has become the de facto default for most new networking code.

Embedded and no_std Rust: systems programming with no operating system at all

Everything in this guide so far has assumed a Linux process with the full standard library available. Rust also supports #![no_std], compiling without the standard library's OS-dependent portions (file I/O, threads, networking, anything that assumes a host OS is present) for targets with no operating system underneath at all, a microcontroller's bare-metal firmware being the canonical case, covered in depth by this site's dedicated Embedded topic. A no_std binary still has access to core, the OS-independent subset of the standard library covering the type system, iterators, and the ownership and borrowing rules this entire guide has described; only the parts that fundamentally assume an OS's presence are unavailable.

rust
#![no_std]
#![no_main]

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

#[no_mangle]
pub extern "C" fn _start() -> ! {
    loop {
        // bare-metal firmware logic here, with no OS, no heap by default,
        // and no std::fs or std::net available at all
    }
}

This is a genuinely different programming model from everything else in this guide, closer to the embedded C posts elsewhere on this site than to anything requiring a Linux kernel underneath, and it is worth knowing it exists specifically because it demonstrates that Rust's core safety guarantees, the borrow checker, ownership, Send/Sync, do not depend on an operating system being present at all; they are properties of the language and its type system, checked by the compiler regardless of what, if anything, is running underneath the compiled binary.

Profiling Rust systems code

perf, the Linux profiler this site's own Performance topic covers in depth for C and C++, works identically against a Rust binary, since the compiled output is ordinary machine code with no runtime interpretation layer sitting between the profiler and the executing instructions. The one Rust-specific wrinkle worth knowing: cargo build --release strips debug symbols by default in some configurations, which makes perf report's output considerably less readable (raw addresses instead of function names); setting debug = true under [profile.release] in Cargo.toml restores symbol information in an otherwise fully optimized release build, trading a larger binary for a profiler that can actually attribute time to named functions.

Text
[profile.release]
debug = true
Text
$ cargo build --release
$ perf record --call-graph dwarf ./target/release/my_systems_tool
$ perf report

Reading the resulting flame graph or call-tree output requires no Rust-specific knowledge beyond recognizing Rust's own name-mangling scheme in symbol names (considerably more verbose than C's plain names, though rustfilt demangles them back to readable form), since the actual profiling data, cycles spent, cache misses, branch mispredictions, means exactly the same thing it means for a C or C++ binary profiled with the identical tool.

Signal handling and the same async-signal-safety constraint

Rust's standard library has no built-in signal handler installation API, deliberately, because a signal handler interacting with Rust's runtime (which includes a panic-handling and unwinding machinery the language itself depends on) safely is considerably more constrained than a typical function, exactly the same async-signal-safety constraint the companion C++ guide covers for POSIX signal handlers in general. The signal-hook crate is the community-standard, carefully-audited way to install a handler in Rust, and it follows the identical discipline this site's other posts recommend: the handler itself does almost nothing beyond setting an atomic flag, with all real work deferred to the main program loop checking that flag outside signal context.

signal_demo.rsrust
use signal_hook::flag;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;

fn main() -> Result<(), std::io::Error> {
    let term = Arc::new(AtomicBool::new(false));
    flag::register(signal_hook::consts::SIGTERM, Arc::clone(&term))?;

    println!("running; send SIGTERM to stop");
    while !term.load(std::sync::atomic::Ordering::Relaxed) {
        // ordinary work here
    }

    println!("stopping cleanly");
    Ok(())
}

AtomicBool here plays exactly the role std::atomic<bool> plays in the C++ signal-handler post: a lock-free, allocation-free flag safe to write from a signal-interrupted context and safe to read from the main loop, with no lock and no allocation on either side of that boundary.

Crate security auditing and the supply-chain surface

Cargo's package ecosystem, crates.io, makes adding a dependency trivially easy, a single line in Cargo.toml and a rebuild, which is a genuine productivity win and a genuine new risk surface C and C++ systems code, with its traditionally much smaller and more manually-vetted set of third-party dependencies, has historically faced in a different form. cargo audit (a separate tool, installed with cargo install cargo-audit) checks a project's dependency tree against the RustSec security advisory database, flagging any crate version with a known, published vulnerability, which is worth running as a standing part of CI for any systems project with a non-trivial dependency tree, exactly the discipline a project pulling in any third-party C library would also want but has historically had less tooling support for doing automatically.

Text
$ cargo install cargo-audit
$ cargo audit
    Fetching advisory database from `https://github.com/RustSec/advisory-db.git`
      Loaded 687 security advisories
    Scanning Cargo.lock for vulnerabilities (42 crate dependencies)

A clean cargo audit run is not a guarantee a dependency is free of bugs entirely, only that no published, known vulnerability currently matches a crate version in the tree; it is a floor, not a ceiling, the same honest framing this site's security-focused posts apply to any automated scanning tool rather than treating a clean scan as equivalent to a manual review.

Cross-compiling for embedded Linux targets

A systems program destined for an embedded Linux board, an ARM-based single-board computer or a custom BSP covered in this site's Embedded Linux topic, is typically built on a faster x86-64 development machine and cross-compiled for the target's actual architecture, which Rust's toolchain supports directly through rustup target add and a target triple naming the destination CPU and ABI.

Text
$ rustup target add aarch64-unknown-linux-gnu
$ cargo build --release --target aarch64-unknown-linux-gnu

The resulting binary at target/aarch64-unknown-linux-gnu/release/ is a native ARM64 ELF executable, not requiring any emulation or interpretation layer on the target device, exactly as a cross-compiled C or C++ binary built with an ARM GCC toolchain would be; Rust's rustc shares LLVM as its code-generation backend with Clang, which is part of why cross-compilation support for a given target architecture tends to track closely with whichever architectures LLVM itself supports well. A build that links against the target's own C library (glibc in the triple above) rather than a statically-linked alternative (musl, selected with a -musl target triple instead) needs that C library's development headers and a matching sysroot available to the cross-compiling toolchain, the same cross-compilation sysroot concern this site's Embedded Linux posts describe for C and C++ cross-builds generally.

Const generics and compile-time guarantees for fixed-size buffers

Rust's const generics, stabilized progressively through recent editions, let a type's size itself be a compile-time parameter, which is directly relevant to systems code working with fixed-size protocol buffers or hardware register layouts, the same domain the companion C++ guide's std::span<T, N> static-extent feature addresses from the other language's side of an equivalent idea.

const_generic_buffer.rsrust
struct FixedBuffer<const N: usize> {
    data: [u8; N],
    len: usize,
}

impl<const N: usize> FixedBuffer<N> {
    fn new() -> Self {
        FixedBuffer { data: [0u8; N], len: 0 }
    }

    fn push(&mut self, byte: u8) -> Result<(), &'static str> {
        if self.len >= N {
            return Err("buffer full");
        }
        self.data[self.len] = byte;
        self.len += 1;
        Ok(())
    }
}

fn main() {
    let mut buf: FixedBuffer<16> = FixedBuffer::new();
    for i in 0..16 {
        buf.push(i as u8).unwrap();
    }

    match buf.push(99) {
        Ok(_) => println!("unexpected success"),
        Err(e) => println!("expected failure: {}", e),
    }
}
Text
$ rustc -O const_generic_buffer.rs -o const_generic_buffer
$ ./const_generic_buffer
expected failure: buffer full

FixedBuffer<16> and FixedBuffer<32> are genuinely distinct types at compile time, the same way std::span<T, 16> and std::span<T, 32> are distinct in the C++ type system, which means a function requiring a buffer of exactly one specific size can declare that requirement directly in its signature and have the compiler enforce it, rather than checking the size at runtime the way a dynamically-sized buffer parameter would need to.

Where Rust's guarantees stop

Every guarantee this guide has described holds for safe Rust; none of them extends automatically into an unsafe block, a raw FFI call, or a logic error that compiles cleanly but is simply wrong. A correctly-marked unsafe block whose actual pointer arithmetic is wrong is still undefined behavior, exactly as wrong C++ pointer arithmetic is, with the unsafe keyword only marking where that responsibility was explicitly taken on, not proving it was discharged correctly. A deadlock between two Mutex instances locked in inconsistent order across two threads compiles and runs with no warning from the borrow checker at all, since lock ordering is a runtime property the type system does not track. Treat this guide's safety guarantees the way the companion C++ guide treats RAII and std::span: each closes off one specific, well-understood bug category, and the remaining surface, logic errors, unsafe code, lock ordering, still needs the same careful review and testing discipline systems programming has always required, in any language.

Linting with Clippy beyond what the compiler alone checks

rustc itself catches every genuine safety violation covered in this guide, but a large class of code that compiles correctly and runs correctly can still be written in a way that is needlessly inefficient, unclear, or a common mistake pattern the language allows without being technically wrong. Clippy, Rust's official linter and a rustup component by default, catches this broader category, flagging, among hundreds of checks, an unnecessary clone() where a borrow would do, a match that could be a simpler if let, or an integer comparison that can never be true given the types involved.

Text
$ cargo clippy
warning: used `unwrap()` on a `Result` value
  --> src/main.rs:12:19
   |
12 |     let file = File::open(path).unwrap();
   |                   ^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(clippy::unwrap_used)]` on by default in some configurations
   = help: consider using `expect()` with a descriptive message, or handling the `Err` case

Running cargo clippy as a standing part of CI, with #[deny(clippy::all)] or a narrower selected set of lints promoted from warnings to hard errors, is the Rust-ecosystem equivalent of the -Wall -Wextra -Werror discipline the companion C++ guide recommends adopting as a project-wide default rather than an occasional, optional check; the specific lints differ by language, but the underlying practice, treating the linter's own warnings as a continuously enforced floor rather than advice to read occasionally, transfers directly.

A worked comparison: the same task in C, C++, and Rust

Tying this guide back to its two companion posts on this site with one concrete, shared example: reading a file's contents into memory and reporting its size behaves identically at the syscall level in all three languages, since all three ultimately call the same open/read/close sequence underneath. The C version, covered in this site's own systems-programming posts, needs explicit error checking after every call and manual close() on every exit path. The C++ version, built with the RAII file-descriptor wrapper from the companion guide, closes the descriptor automatically through a destructor but still relies on the programmer to have written that wrapper's copy-and-move semantics correctly. The Rust version below achieves the same automatic cleanup through Drop, with no equivalent risk of an incorrectly implemented move constructor, because Rust's ownership model, not a hand-written class, is what guarantees a File has exactly one owner at a time.

compare_task.rsrust
use std::fs::File;
use std::io::Read;

fn file_size(path: &str) -> std::io::Result<usize> {
    let mut file = File::open(path)?;
    let mut buf = Vec::new();
    file.read_to_end(&mut buf)?;
    Ok(buf.len())
    // file's Drop runs here automatically, on every exit path including the ? returns above
}

fn main() {
    match file_size("/etc/hostname") {
        Ok(size) => println!("{} bytes", size),
        Err(e) => eprintln!("error: {}", e),
    }
}
Text
$ rustc -O compare_task.rs -o compare_task
$ ./compare_task
9 bytes

The three versions produce identical runtime behavior and nearly identical generated machine code once optimized, since all three ultimately bottom out in the same syscalls; what differs between them is entirely in how much of the surrounding correctness, closing the descriptor, not using it after close, not racing it across threads, is enforced by the compiler versus left to the programmer's own discipline, which is the single thread running through every comparison this guide has drawn between Rust and its two companion languages on this site.

Choosing between Rust and C++ for a new systems project

This guide has avoided framing Rust and C++ as a strict replacement relationship, since the honest answer depends heavily on the specific project. A new systems project with no existing C or C++ codebase to integrate with, where the team can invest in learning Rust's ownership model up front, gains real, measurable safety benefits this guide has walked through concretely: fewer categories of bug possible at all, caught at compile time rather than discovered through a sanitizer run or, worse, in production. A project that must integrate deeply with an existing, large C++ codebase, link against C++-specific libraries with complex class hierarchies, or retain a team's existing deep C++ expertise, often finds incremental adoption, a new component written in Rust and linked in through the FFI boundary this guide covered, a more pragmatic path than a wholesale rewrite, which carries its own well-documented risks regardless of which language the rewrite targets. Neither choice is wrong in the abstract; the right one depends on the codebase's actual constraints, not on which language's safety story sounds more compelling in isolation.

Teams that have gone through an incremental adoption successfully tend to pick a genuinely self-contained component for the first Rust piece, a parser, a codec, a well-isolated service, rather than something tightly entangled with the rest of the codebase's existing object hierarchy, precisely because the FFI boundary this guide has described is cleanest when it separates two components with a narrow, well-defined contract between them rather than a sprawling, bidirectional dependency that would need constant round-tripping across the language boundary for every call.

Keeping up with a fast-moving language

Rust ships a new stable release every six weeks, considerably faster than C++'s roughly three-year standard revision cycle, which means a feature like const generics or a stabilized API in std can go from nightly-only to broadly available in production code within a year or two of its initial proposal, a pace this guide's own examples benefit from (several of the features shown, std::process::exit, the ? operator, const generics among them, were themselves added across different stable releases over the language's history) but also one worth tracking deliberately through the official release notes rather than assuming a feature seen in a blog post or an older tutorial is necessarily available on whichever toolchain version a given project has pinned. rustup show reports the currently active toolchain version, and rustup update pulls the latest stable release, which is worth running before assuming a newer language feature mentioned elsewhere is unavailable on a system that simply has not been updated recently.

A closing note on where to go next

This guide has covered the language-level mechanisms, ownership, Result, unsafe, and the ecosystem tools, Cargo, Clippy, Miri, cargo audit, that distinguish Rust systems programming from its C and C++ counterparts on this site, without attempting to be a complete reference to the language itself; the official Rust Book and the standard library's own documentation remain the canonical, continuously updated source for details this guide necessarily simplified or omitted. Readers coming from the companion C and C++ guides on this site are best served by treating each concrete example here as a direct point of comparison against the equivalent pattern in whichever of those two languages they already know well, since the actual syscalls and runtime behavior underneath rarely differ at all; what differs, consistently, is how much of the surrounding bookkeeping a compiler checks for you before the program ever runs.

Treat the release-note habit as part of maintaining a Rust project, the same way checking GCC and Clang's own version-support pages, as the companion C++ guide recommends, is part of maintaining a C++ one.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.