Search code examples
textmacrosformattingrustembedded

How can I use the format! macro in a no_std environment?


How could I implement the following example without using std?

let text = format!("example {:.1} test {:x} words {}", num1, num2, num3);

text has type &str and num1, num2 and num3 have any numeric type.

I've tried using numtoa and itoa/dtoa for displaying numbers but numtoa does not support floats and itoa does not support no_std. I feel like displaying a number in a string is fairly common and that I'm probably missing something obvious.


Solution

  • In general, you don't. format! allocates a String, and a no_std environment doesn't have an allocator.

    If you do have an allocator, you can use the alloc crate. This crate contains the format! macro.

    #![crate_type = "dylib"]
    #![no_std]
    
    #[macro_use]
    extern crate alloc;
    
    fn thing() {
        let text = format!("example {:.1} test {:x} words {}", 1, 2, 3);
    }
    

    See also: