no_std
- Rust course
- Expert
- Lesson 31/46
- 4 min
Learn the no-stdlib environment with #![no_std].
no_std
The standard library has three layers: core (needs no operating system or allocator: Option, Result, iterators, slices, fmt), alloc (needs an allocator: Vec, String, Box) and std (needs an operating system: files, threads, networking). With #![no_std] only core is used; microcontrollers, kernels and bootloaders run in this environment:
#![no_std]
pub fn en_buyuk(v: &[u32]) -> Option<u32> {
v.iter().copied().max() // all in core
}Many types in std are really re-exported from core or alloc; std::option::Option and core::option::Option are the same type.
What's in core?
core contains primitive types and their methods, Option/Result, iterators, slice and str operations, cmp, mem, ptr, fmt (formatting, but not printing to a screen), atomics and Cell/RefCell. Missing: heap types, println!, files, threads, HashMap (needs the OS for a random seed).
let m = core::cmp::max(3, 7);
let n = core::mem::size_of::<u64>();
let ilk = core::str::from_utf8(b"rust").ok();Practice Work with core
Write fn en_buyuk(v: &[u32]) -> Option<u32> using only core paths. Print the results of core::cmp::max(3, 7), en_buyuk(&[4, 9, 2]) and core::mem::size_of::<u64>() separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn en_buyuk(v: &[u32]) -> core::option::Option<u32> {
v.iter().copied().max()
}
fn main() {
println!("{} {:?} {}", core::cmp::max(3, 7), en_buyuk(&[4, 9, 2]), core::mem::size_of::<u64>());
}Expected output
7 Some(9) 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is a library written to be <code>no_std</code> compatible?
- Because it's mandatory
- For less code
- So it can be used everywhere, including embedded systems and WebAssembly Correct answer
- Because it's faster
Explanation: Many crates make std an optional feature: default = ["std"], and no_std users turn it off.
2 Only core
#![____]
pub fn en_buyuk(v: &[u32]) -> Option<u32> {
v.iter().copied().max()
}
#![no_std]
pub fn en_buyuk(v: &[u32]) -> Option<u32> {
v.iter().copied().max()
}
Explanation: #![no_std] makes the crate use only core.
3 Item and layer
| Term | Meaning |
|---|---|
Option, iter, fmt |
core |
Vec, String, Box |
alloc |
fs, thread, net |
std |
HashMap |
std (OS for the seed) |