A Rust String can hold a dynamically sized message, such as formatted firmware diagnostics. In no_std firmware, using it requires the alloc crate and a global allocator. section 7.2.4 section 1.3.1
#![no_std]
#![no_main]
extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use cortex_m_rt::entry;
use embedded_alloc::LlffHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
fn record_event(log: &mut Vec<String>, source: &str, code: u32) {
log.push(format!("{}: code 0x{:08x}", source, code));
}
#[entry]
fn main() -> ! {
unsafe { embedded_alloc::init!(HEAP, 4096); }
let mut log: Vec<String> = Vec::new();
record_event(&mut log, "uart", 0x0001);
record_event(&mut log, "i2c", 0x002a);
record_event(&mut log, "gpio", 0x00ff);
for entry in &log {
defmt::info!("{}", entry.as_str());
}
loop {}
}
The example records formatted UART, I2C, and GPIO messages in a growing Vec<String>, then iterates over them for logging. section 7.2.4
Account for allocation behavior when choosing String in firmware:
- format! allocates a String; a growing Vec<String> may also allocate a larger backing array when its capacity runs out. section 7.2.4
- If allocation fails, the default alloc APIs invoke the panic handler; try_reserve offers a fallible capacity request that returns a Result. section 7.2.4
- Without a heap, use fixed-size storage or write into a heapless::String instead. section 7.2.4



























