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

  • A+
Category:Languages

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.


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.

This crate is not stabilized, so you need to use nightly Rust:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: