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 aString
, and ano_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.See also:
In addition to Shepmaster's answer you can also format strings without an allocator.
In
core::fmt::Write
you only need to implementwrite_str
and then you getwrite_fmt
for free.With
format_args!(...)
(same syntax asformat!
) you can prepare acore::fmt::Arguments
value, which can be passed tocore::fmt::write
.See Playground: