liveBook · Manning

String

As explained in Embedded Software with Rust

A string is a sequence of characters represented as data.

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

How Embedded Software with Rust covers it

How deep it goes
Explains formatting and collection allocations, growth, and failure handling, but does not detail String internals.
Examples
Uses a growing diagnostic log of formatted UART, I2C, and GPIO messages.
What it assumes
Requires opting into alloc and supplying a global allocator for heap-backed strings in no_std firmware.
What you can do after
Apply String in no_std firmware by supplying a global allocator and accounting for allocation failure.
How it connects
Connects String to Vec, heap allocation, alloc, no_std, and fixed-capacity alternatives.

Also explained in

Compare how 28 books explain string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.