5

I have a count: u32 that I need to push through a TCP stream as its ASCII byte representation. For example if the value is 42, I want to write the bytes [52, 50] (ASCII for "42") to the stream.

I can do this by first creating a String with:

use std::io::prelude::*;

fn write_number<T: Write>(writer: &mut T, num: u32) -> std::io::Result<usize> {
    let num_as_str: String = num.to_string();
    let num_as_bytes = num_as_str.as_bytes();
    writer.write(num_as_bytes)
}

Is this is a wasteful way of doing this? I don't feel that allocating a String should be necessary for this task. Is there a more efficient way to implement write_number? I've tried going through str, but str does not implement From<u32>.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
knix
  • 76
  • 4
  • 3
    Note that the linked question does *more* than you asked; all you need to know about to avoid allocating a `String` is the `write!` macro (`writeln!` also exists). Also see [How can I append a formatted string to an existing String?](https://stackoverflow.com/q/28333612/3650362) (which applies to more than just `String`s) and [How to send output to stderr](https://stackoverflow.com/q/27588416/3650362). – trent Mar 13 '19 at 22:09
  • 4
    Based on that answer, it appears I can simply do `write!(writer, "{}", num)`. I now understand why the `Display` trait works the way it does. Thanks! – knix Mar 13 '19 at 22:24

0 Answers0