Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 132 ยท Advanced Rust

Embedded, no_std and WebAssembly

Learn what #![no_std] means, how core, alloc and std differ, how embedded HAL traits work and how Rust compiles to WebAssembly, with runnable stand-ins for code you cannot run online.

Rust runs in places where most languages cannot: a microcontroller with 16 KB of memory and no operating system, the kernel of an OS, a browser tab as WebAssembly. The reason is that the language itself needs very little. Everything that depends on an operating system (files, threads, networking, a heap allocator, even println!) lives in the standard library, and Rust lets you leave it out.

This lesson explains how that works: the three layers core, alloc and std, the #![no_std] attribute, panic handlers, how embedded code talks to hardware through traits and volatile memory, and how the same crate compiles to WebAssembly for a browser. Be honest about one thing from the start: our online editor builds ordinary programs with std, and it cannot produce a bare-metal binary or a .wasm file. So the build commands and project files below are read-only sessions that you run on your own machine. For every concept, we also give a runnable stand-in, plain Rust that you can execute here and that teaches the same idea.

core, alloc and std

The standard library is really three libraries stacked on top of each other:

Layer Needs Contains
core nothing: no OS, no heap primitives, Option, Result, iterators, slices, str, fmt, cell, mem, ptr, atomics, ops, marker
alloc a global allocator Box, Vec, String, Rc, Arc, BTreeMap, format!
std an operating system files, networking, threads, HashMap (needs random seeds), Mutex, println!, env, process, time

std re-exports everything from core and alloc, so std::option::Option and core::option::Option are the same type, and std::fmt is core::fmt. When you write a crate with #![no_std], the compiler stops adding extern crate std; and the prelude changes to the smaller core prelude. You can still use any core item, and you can opt in to the heap with extern crate alloc; provided you register a global allocator.

Library authors use this to write portable crates: if a parser, a checksum or a data structure only needs core (and maybe alloc), it works on a laptop, in a kernel and in a browser. Many popular crates are no_std-compatible and say so with a Cargo feature, usually named std.

What breaks when you remove std

Take a program with #![no_std] and try to use the familiar things:

Rust Using std items in a no_std crate (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports error: cannot find macro println in this scope and error[E0433]: cannot find type Vec in this scope: neither lives in core. It also complains error: #[panic_handler] function required, but not found, because without std nobody tells the runtime what to do when a panic happens. A fourth error, "unwinding panics are not supported without std", appears because we compile with plain rustc; in a Cargo project panic = "abort" removes it. That is the second big difference, covered next.

Such a crate also has no fn main in the usual sense. On a microcontroller the entry point is a reset vector, set up by a runtime crate and a linker script, so the program is #![no_main]. That is why we cannot run it in the browser editor.

The panic handler

In a std program a panic prints a message and unwinds the stack or aborts. A no_std binary must define what happens itself, with exactly one function marked #[panic_handler]:

Rust
// Read-only: a typical embedded handler. It cannot run in our online editor.
use core::panic::PanicInfo;

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    // Log `info` over a serial port if you have one, then stop or reset the chip.
    loop {}
}

The return type ! (never) means the function must not return (Type System Techniques). In practice you use ready-made crates: panic-halt stops, panic-reset restarts the chip, panic-probe prints through a debug probe. You also set panic = "abort" in the Cargo profile, because there is no unwinding machinery to link.

An embedded project, read-only

A complete minimal firmware for an ARM Cortex-M board looks like this. Nothing in these four blocks can be built in our editor.

TOML
# Cargo.toml (read-only)
[package]
name = "blink"
version = "0.1.0"
edition = "2024"

[dependencies]
cortex-m = "0.7"
cortex-m-rt = "0.7"
panic-halt = "1"

[profile.release]
opt-level = "s"     # optimize for size
lto = true
panic = "abort"
TOML
# .cargo/config.toml (read-only)
[build]
target = "thumbv7em-none-eabihf"   # Cortex-M4F/M7F with hardware floats

[target.thumbv7em-none-eabihf]
rustflags = ["-C", "link-arg=-Tlink.x"]   # linker script from cortex-m-rt
Rust
// src/main.rs (read-only)
#![no_std]
#![no_main]

use cortex_m_rt::entry;
use panic_halt as _; // links the panic handler

#[entry]
fn main() -> ! {
    // Configure pins, timers, peripherals here.
    loop {
        cortex_m::asm::nop();
    }
}
Terminal
# Terminal (read-only)
rustup target add thumbv7em-none-eabihf
cargo build --release
cargo size --release        # from cargo-binutils: how many bytes of flash?
probe-rs run --chip STM32F411RETx target/thumbv7em-none-eabihf/release/blink

There is also a memory.x file that tells the linker how much flash and RAM your chip has. The essential idea is the target triple: thumbv7em-none-eabihf names the architecture (thumbv7em), the vendor/OS (none: no operating system) and the ABI (eabihf). Tier 2 targets such as this one come with a precompiled core, which rustup target add downloads.

Runnable stand-in 1: formatting without a heap

On a microcontroller you cannot call format! because it allocates a String. But core::fmt does not allocate: it writes through a trait, core::fmt::Write, one piece at a time. You can implement that trait for a fixed-size buffer on the stack. The code uses only core, so it would compile unchanged in a no_std crate.

Rust core::fmt::Write into a fixed buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The write! macro works on any fmt::Write, so all the formatting power of {:.1} and {:#06x} is available without a heap. This is how crates such as heapless and arrayvec give you string and vector types of fixed capacity: the capacity is a const generic parameter (Const Generics), and a full buffer returns an error instead of growing.

Runnable stand-in 2: collections with fixed capacity

Without alloc there is no Vec. A stack with a compile-time capacity is easy to write on top of an array. [const { None }; N] (inline const, Rust 1.79) initializes an array of non-Copy values.

Rust A heapless stack with const generics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

(The demo uses String only to keep the output readable; the container itself needs no allocation.) The size line shows that everything is inline: the whole structure lives wherever you put it, on the stack or in a static.

Talking to hardware: traits and HAL crates

The embedded ecosystem is built around traits. The embedded-hal crate (version 1.0) defines traits such as OutputPin, InputPin, SpiBus, I2c and DelayNs. Each chip family ships a HAL crate (hardware abstraction layer) that implements those traits for its pins and peripherals. A driver for a temperature sensor is then written once, generically over I2c, and works on any chip. This is the trait bounds machinery from earlier lessons put to work, with zero run-time cost because generics are monomorphized.

A bonus: since drivers depend on traits, you can test them on your PC with a mock that implements the same trait. Here is a miniature version of the idea, with trait names that mirror embedded-hal:

Rust A hardware-independent LED blinker with a mock pin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The same Led and blink code compiles for a real chip: only the pin type changes. Notice the Result plumbing with ? (The ? Operator): hardware can fail, and the associated type Error lets each HAL choose its own error type.

Memory-mapped registers and volatile access

On a microcontroller, peripherals appear as special memory addresses: writing a 32-bit value to 0x4002_0014 might switch on a pin. The compiler must not reorder, merge or delete such accesses, so you use core::ptr::read_volatile and write_volatile. Real projects get these wrapped by generated crates (PACs) so you never write the raw addresses yourself. The runnable version below uses an ordinary variable as the "hardware":

Rust Volatile reads and writes on a fake UART

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Volatile is about the compiler, not about threads: it does not make an access atomic, and it is not a synchronization tool. For data shared with an interrupt handler you still need atomics or a critical section (Atomics).

WebAssembly

WebAssembly (Wasm) is a compact binary format that browsers, servers and edge runtimes can run at near-native speed in a sandbox. Rust is one of the best-supported languages for it. The two most important targets are:

  • wasm32-unknown-unknown: no operating system at all; you talk to the host (usually JavaScript) through imported and exported functions. This is the browser target.
  • wasm32-wasip1 and wasm32-wasip2: the WASI targets, which add a standard interface for files, clocks and sockets, for running outside the browser. (WASI preview 1 was previously called wasm32-wasi; check rustup target list for the current names on your toolchain.)

On wasm32-unknown-unknown, std exists but most of the OS parts (files, threads, processes) return an error or panic at run time. A crate that is no_std + alloc is the most portable choice.

Exporting a function

Wasm functions accept and return only numbers (i32, i64, f32, f64). You export one with extern "C" and, in the 2024 edition, #[unsafe(no_mangle)], so the symbol keeps its exact name. (Before the 2024 edition the attribute was written #[no_mangle]; it is unsafe because a duplicate symbol name can break the program.) On a normal target the function is just an ordinary Rust function, so you can test it right here:

Rust An exported function is a plain function on your PC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Built with the commands below, the library's .wasm file exports add and clamp_percent, and JavaScript can call them directly:

Terminal
# Terminal (read-only): Cargo.toml needs  [lib] crate-type = ["cdylib"]
rustup target add wasm32-unknown-unknown
cargo build --release --target wasm32-unknown-unknown
JavaScript
// JavaScript in the browser (read-only)
const { instance } = await WebAssembly.instantiateStreaming(fetch("blink.wasm"));
console.log(instance.exports.add(40, 2)); // 42

Strings and objects: the memory boundary

Numbers are easy. A string is a different story: the module has one block of linear memory, and the host and the module exchange a pointer and a length into it. The caller asks the module to allocate space, writes the UTF-8 bytes there, calls the function, and reads the result back the same way. This is tedious and error-prone by hand, so a tool called wasm-bindgen generates the glue. To see what it automates, here is the protocol simulated with a Vec<u8> as linear memory:

Rust Passing a string through linear memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

With wasm-bindgen you write the natural Rust signature and the tool generates both the Rust glue and a JavaScript wrapper:

Rust
// src/lib.rs (read-only; needs the wasm-bindgen crate)
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}

#[wasm_bindgen]
pub struct Counter {
    value: u32,
}

#[wasm_bindgen]
impl Counter {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Counter {
        Counter { value: 0 }
    }

    pub fn increment(&mut self) -> u32 {
        self.value += 1;
        self.value
    }
}
Terminal
# Terminal (read-only)
cargo install wasm-pack
wasm-pack build --target web
JavaScript
// index.html module script (read-only)
import init, { greet, Counter } from "./pkg/my_crate.js";

await init();                 // downloads and instantiates the .wasm file
console.log(greet("Ferris")); // "Hello, Ferris!"
const counter = new Counter();
counter.increment();

The web-sys and js-sys crates add typed bindings to the browser's DOM and JavaScript built-ins, and frameworks such as Leptos, Yew and Dioxus build whole user interfaces on top of them. All of these crates need Cargo, so they are outside the scope of our editor.

Size, speed and practical advice

  • Size. Wasm and firmware are often size-limited. Use opt-level = "s" or "z", lto = true, codegen-units = 1, panic = "abort" and strip = true in [profile.release]; run wasm-opt -Oz (from the Binaryen tools) on the output. Formatting machinery ({:?}, {:.3}) is a major source of code size.
  • Avoid hidden allocation. In firmware, prefer fixed-capacity types and decide at compile time how much memory each part may use.
  • Make crates portable. Put #![no_std] at the top, add extern crate alloc; only if you need the heap, and gate std behind a Cargo feature (#![cfg_attr(not(feature = "std"), no_std)]).
  • Test on the PC. Keep hardware access behind traits, test the logic with mocks (as shown), and use cargo test on your host.
  • Know the ecosystem. Embedded Rust: the Embedded Rust Book, embedded-hal, embassy (async firmware), probe-rs. WebAssembly: wasm-bindgen, wasm-pack, trunk, the WASI runtimes wasmtime and wasmer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which crate layer provides Vec and String but not files or threads?

    alloc adds heap-based types such as Box, Vec and String; it needs a global allocator but no operating system. std adds the operating system features on top.
  2. 2. What must a #![no_std] binary define that a normal program gets from std?

    Without std nothing decides what a panic does, so exactly one #[panic_handler] (usually from a crate such as panic-halt) is required.
  3. 3. Why does the embedded ecosystem use traits such as OutputPin and DelayNs?

    Generic code over HAL traits works on every chip that implements them, and a mock implementation lets you test the logic on a PC. Monomorphization means no run-time cost.
  4. 4. What does read_volatile/write_volatile guarantee?

    Volatile accesses are performed exactly as written, which matters for hardware registers. They are not atomic and not a synchronization tool, and the pointer must still be valid.
  5. 5. Which values can cross the boundary between JavaScript and a plain WebAssembly function directly?

    Plain Wasm exports take and return numbers. Strings travel as a pointer and length into linear memory, which wasm-bindgen automates.

Summary

  • core needs nothing, alloc needs an allocator, std needs an operating system; #![no_std] limits a crate to core (plus alloc if you ask).
  • A no_std program needs a #[panic_handler], usually panic = "abort", and on a microcontroller a runtime crate with #![no_main].
  • core::fmt::Write, const-generic buffers and fixed-capacity collections give you formatting and data structures without a heap.
  • Embedded Rust is trait-based: embedded-hal traits, chip-specific HALs, generic drivers and mock-based tests on the PC; registers are accessed with volatile reads and writes.
  • WebAssembly targets are wasm32-unknown-unknown (browser) and wasm32-wasip1/wasip2 (WASI); exports use extern "C" and #[unsafe(no_mangle)], and wasm-bindgen automates strings and objects.
  • Our editor can only run the std stand-ins; use your own toolchain for the build commands shown as read-only.

Next: What's New in Rust 2021 to 1.99