alloc crate
- Rust course
- Expert
- Lesson 32/46
- 4 min
Use the heap with the alloc crate.
The alloc crate
If there's a memory allocator, no_std code can use the alloc crate to reach Vec, String, Box, Rc, BTreeMap and format!:
#![no_std]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use alloc::format;
pub fn rapor(v: &[u32]) -> String {
let ciftler: Vec<u32> = v.iter().copied().filter(|x| x % 2 == 0).collect();
format!("{} çift", ciftler.len())
}The application provides the allocator: on embedded systems a crate like embedded-alloc is registered with #[global_allocator].
alloc within std
The alloc crate can be used explicitly in normal programs too; it's a way to show the code is ready to move to no_std:
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
let mut v: Vec<i32> = Vec::new();
v.push(1);
let s = String::from("merhaba");std::vec::Vec and alloc::vec::Vec are the same type; only the path differs.
Practice alloc types
Write extern crate alloc; and use alloc::vec::Vec and alloc::string::String. Create a vector holding 1 and 2 and the text "merhaba", and print both separated by a space (the vector with {:?}).
Starter code
fn main() {
// buraya yaz
}Sample solution
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);
let s = String::from("merhaba");
println!("{:?} {}", v, s);
}Expected output
[1, 2] merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is <code>HashMap</code> not in alloc while <code>BTreeMap</code> is?
- Both are there
- HashMap's default hasher needs a random seed from the OS Correct answer
- HashMap is slower
- BTreeMap is newer
Explanation: In a no_std environment, the hashbrown crate provides a HashMap with your own hash function.
2 Allocation crate
extern crate ____;
use alloc::vec::Vec;
extern crate alloc;
use alloc::vec::Vec;
Explanation: extern crate alloc; makes heap types usable in no_std.
3 Path and type
| Term | Meaning |
|---|---|
alloc::vec::Vec |
Dynamic array |
alloc::string::String |
Owned text |
alloc::boxed::Box |
Heap box |
alloc::collections::BTreeMap |
Sorted map |