Rust
no_std
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();
Exercise 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.
Show example 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>());
}
Test yourself
-
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
- Because it's faster
Show answer
So it can be used everywhere, including embedded systems and WebAssembly — Many crates make std an optional feature: default = ["std"], and no_std users turn it off.
-
Only core
#![____]
pub fn en_buyuk(v: &[u32]) -> Option<u32> {
v.iter().copied().max()
}
Show answer
#![no_std]
pub fn en_buyuk(v: &[u32]) -> Option<u32> {
v.iter().copied().max()
}
-
Item and layer
- Option, iter, fmt
- core
- Vec, String, Box
- alloc
- fs, thread, net
- std
- HashMap
- std (OS for the seed)
Next lesson: alloc crate