skip to content

In Rust, what does `#![no_std]` take away from a crate, and what do the `core` and `alloc` crates still provide?

level: juniorimportance: must knowfreq 38%

answer

  1. three layers of the library
  2. no OS, no heap assumed
  3. heap types need an opt-in crate
  4. the prelude changes too
  5. f64::sqrt is not in core

basics

~20 s

#![no_std] stops std being linked and gives every module the core prelude. core keeps primitives, Option, Result, slices, iterators, fmt and atomics; alloc, added with extern crate alloc, brings Vec, String and Box; I/O, threads and HashMap stay in std.

solid answer

~40 s

`#![no_std]` at the crate root means `std` is not linked automatically and the standard-library prelude becomes the `core` prelude, so `Vec`, `String`, `Box`, `vec!` and `format!` are not even in scope. Rust's library is layered. `core` assumes no operating system and no heap: primitive types, `Option` and `Result`, slices and `str`, iterators, `core::fmt`, `core::cell`, atomics, `Duration`. `alloc` assumes only a global allocator and adds `Vec`, `String`, `Box`, `Rc`, `BTreeMap` and `VecDeque` (plus `Arc` where the target has pointer-sized atomics); under Cargo it must be named with `extern crate alloc;`. Everything that needs an OS stays in `std`: files, sockets, threads, `println!`, `HashMap` with its random seed, and float methods such as `f64::sqrt`.

code

rust · 29 lines
rust
#![no_std]

extern crate alloc;

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt::Write;

// core: slices, integers, Option, Result, iterators and fmt. No heap needed.
pub fn checksum(data: &[u8]) -> u16 {
    data.iter().fold(0xFFFF_u16, |crc, &b| {
        (0..8).fold(crc ^ (u16::from(b) << 8), |c, _| {
            if c & 0x8000 != 0 { (c << 1) ^ 0x1021 } else { c << 1 }
        })
    })
}

// alloc: Vec, String, Box, BTreeMap. The final binary must supply the heap.
pub fn report(frames: &[&[u8]]) -> BTreeMap<u16, String> {
    let mut out = BTreeMap::new();
    for frame in frames {
        let mut line = String::new();
        let bytes: Vec<u8> = frame.to_vec();
        write!(line, "{} bytes", bytes.len()).unwrap();
        out.insert(checksum(frame), line);
    }
    out
}

go deeper

for a junior

Recall the three layers: core needs nothing, alloc needs an allocator, std needs an operating system. Name two types from each and know that the prelude switches to core's.

for a middle

Explain why alloc needs extern crate alloc; under Cargo, why HashMap is std-only, and which everyday methods, such as f64::sqrt, quietly vanish without std.

for a senior

Show that no_std is a property of the whole dependency graph: one dependency without the attribute links std again, and only a build for a target without std proves otherwise.

for a principal

Frame core, alloc and std as tiers a library can promise to its users, and weigh what each tier lets the API offer against how many targets it can reach.

## What the attribute changes `#![no_std]` is a crate-level attribute, written once at the top of `lib.rs` or `main.rs`. The Reference gives it two effects: - **`std` is no longer linked automatically**, and `std` drops out of the extern prelude, so a path such as `std::collections::HashMap` fails with E0433 ("cannot find module or crate `std` in this scope"). - **The standard-library prelude switches to the `core` prelude.** On the 2024 edition a `no_std` crate gets `core::prelude::rust_2024` instead of `std::prelude::rust_2024`. That still brings in `Option`, `Result`, `Some`, `None`, `Ok`, `Err`, `Iterator`, `Clone`, `Copy`, `Drop`, the `Fn` traits, `TryFrom` and `Future`, but not `Vec`, `String`, `Box`, `ToString`, `ToOwned`, `vec!` or `format!`. The attribute does **not** promise that `std` is absent from the final program. The Reference warns that a dependency without `#![no_std]`, or an explicit `extern crate std;`, still links it. On a target that has no `std` at all, that shows up as E0463, "can't find crate for `std`". ## Three layers, one library | crate | assumes | typical contents | |---|---|---| | `core` | nothing: no OS, no heap | primitives, `Option`, `Result`, slices, `str`, iterators, `core::fmt`, `core::cell`, `core::sync::atomic`, `core::time::Duration`, `core::net` addresses | | `alloc` | a global allocator | `Vec`, `String`, `Box`, `Rc`, `Arc`, `BTreeMap`, `BTreeSet`, `VecDeque`, `BinaryHeap`, `format!` | | `std` | an operating system | files, sockets, threads, `std::io`, `println!`, `HashMap` and `HashSet`, environment and process APIs | `std` re-exports `core` and `alloc`, which is why `std::option::Option` and `core::option::Option` are the same type: a `no_std` library's types interoperate with a `std` caller's without conversion. ## What surprises people about `core` 1. **No heap types at all.** `Vec`, `String` and `Box` live in `alloc`, so code that uses them needs that crate and, in the final binary, an allocator. 2. **No `HashMap`, even with `alloc`.** `alloc::collections` has `BTreeMap`, `BTreeSet`, `VecDeque`, `BinaryHeap` and `LinkedList`, but `alloc::collections::HashMap` is E0425 ("not found in `alloc::collections`"). The standard map's default hasher is seeded with randomness from the OS, which is why it sits in `std`. `BTreeMap` is the usual replacement. 3. **No float math methods.** On stable 1.99, `x.abs()` on an `f64` compiles in `core`, but `x.sqrt()`, `x.floor()` and `x.powi(2)` fail with E0599, because those methods are defined in `std`. A `core` version exists only behind the unstable `core_float_math` feature. 4. **No `println!`.** There is no standard output. Formatting still works: `core::fmt::Write` and `write!` format into any buffer you supply, such as a UART driver or a fixed-capacity string. 5. **`Arc` depends on the target.** `alloc::sync`, and with it `Arc`, is compiled only for targets with pointer-sized atomics, so it is missing on some small cores even when `Rc` is there. ## Bringing `alloc` back `alloc` ships with the compiler, but Cargo does not pass it with `--extern`, so it is not in the extern prelude even on edition 2018 and later. A crate opts in with: - `extern crate alloc;` at the crate root, then - ordinary paths such as `use alloc::vec::Vec;` or `alloc::string::String`. A **library** can do this freely: it compiles without choosing an allocator. The **binary** that finally links everything must provide exactly one `#[global_allocator]`, or linking stops with "no global memory allocator found but one is required". That is the allocator question's subject. ## Writing code that serves both worlds - Import from `core::` and `alloc::` paths (`core::fmt`, `alloc::vec::Vec`) rather than `std::`. Because `std` re-exports them, the same code compiles in a `std` crate and the types are identical, so a caller holding a `std::vec::Vec` passes it straight in. - Accept borrowed data (`&[u8]`, `&str`) and return `core` types where possible; keep `Vec` and `String` returns for functions that genuinely need ownership. - Format into a caller-supplied `core::fmt::Write` sink instead of returning a `String`. The caller decides whether the sink is a UART, a fixed-capacity string or, in a `std` program, a `String`. - Check the result by building for a target that has no `std`, such as thumbv7em-none-eabihf. A host build always finds `std`, so it cannot show what a dependency drags in. ## Where `no_std` code runs - Firmware on microcontrollers, where there is no OS and often a few kilobytes of RAM. - Bootloaders and kernels, which run before or instead of an OS. - Portable libraries (checksums, parsers, codecs, data structures) that want to serve those users as well as ordinary `std` programs. The rule of thumb: everything in `core` is pure computation over memory you already have; `alloc` adds memory you ask for; `std` adds the world outside the program.

  • In a `#![no_std]` Rust crate, why does `x.sqrt()` on an `f64` fail to compile while `x.abs()` works?
    On stable Rust, `sqrt`, `floor`, `powi` and the other rounding and transcendental methods are defined in `std`, so in a `no_std` crate `x.sqrt()` fails with E0599. `abs` only clears the sign bit and is defined in `core`. Firmware uses a software math crate or the chip's instructions; a `core` version of these methods exists only behind the unstable `core_float_math` feature.
  • Does `#![no_std]` guarantee that `std` is missing from the final Rust binary?
    No. It only stops this crate linking `std` implicitly. A dependency that does not declare `#![no_std]`, or an `extern crate std;` anywhere, links it again. On a host target that goes unnoticed; on a target without `std`, such as thumbv7em-none-eabihf, rustc fails with E0463 and a note naming the crate that requires `std`.
  • Why does a Rust 2024 `#![no_std]` crate still write `extern crate alloc;`, when `extern crate` is otherwise obsolete?
    Since the 2018 edition, crates passed with `--extern` sit in the extern prelude and need no declaration. Cargo passes your dependencies that way but not the compiler's own `alloc` crate, so `alloc` is not in the extern prelude until `extern crate alloc;` adds it. `core` is always there, and `std` is there unless `no_std` is set.

Think of a toolbox in three trays: core is the tray of hand tools that work anywhere, alloc adds power tools that need a socket (the allocator), and std adds the workshop itself, with its building services.

  • Saying `#![no_std]` removes `Option`, `Result` and iterators along with `std`.
  • Expecting `HashMap` to come back once `extern crate alloc` is added.
  • Believing `#![no_std]` guarantees no dependency can link `std`.
  • Assuming `extern crate alloc` also installs a default heap allocator.
  • Calling `f64::sqrt` in core code and blaming a missing import.