Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write string representation of a u32 into a String buffer without extra allocation? [duplicate]

Tags:

string

int

rust

I can convert a u32 into String and append it to an existing string buffer like this

let mut a = String::new();
let b = 1_u32.to_string();
a.push_str(&b[..]);

But this involves allocation of a new string object in the heap.

How to push the string representation of a u32 without allocating a new String?

Should I implement an int-to-string function from scratch?

like image 650
eonil Avatar asked Feb 03 '26 02:02

eonil


1 Answers

Use write! and its family:

use std::fmt::Write;

fn main() {
    let mut foo = "answer ".to_string();

    write!(&mut foo, "is {}.", 42).expect("This shouldn't fail");

    println!("The {}", foo);
}

This prints The answer is 42., and does exactly one allocation (the explicit to_string).

(Permalink to the playground)

like image 118
mcarton Avatar answered Feb 04 '26 16:02

mcarton