Impl <T: Iterator<Item=char>> Display for T

Is there any reason why the language doesn't implement something like this?

impl <T: Iterator<Item=char>> Display for T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
         for next_char in self {
              f.write_char(next_char)?;
         }
         Ok(())
    }
}

It would save a fair bit of memory on intermediate buffers such as collect::<String>() produces. A good example of a use case is converting borrowed byte slices/iterators to byte-slice literals:

pub(crate) fn escaped_bytes_to_string(input: &[u8]) -> String {
    "b\"" + input.iter().flat_map(core::ascii::escape_default).collect() + "\""
}

It'd be a breaking change to add it (without some type of newtype wrapper), since this may already exist.

(And it'd be a bummer if you tried to print my example with your suggested implementation...)

1 Like

Yikes, I guess some truncation would be needed, but we'd have to determine how long an object's Display representation actually needed to be.

Also, TIL a struct can be declared without curlies (I'd always thought it was pub enum Infallible {} and not pub enum Infallible;).

(It's a unit struct,[1] not an empty enum.[2])


  1. with one possible value ↩︎

  2. which has zero ↩︎

There's even a some types in the standard library with both traits implemented like:

1 Like

Display takes &self and requires fmt to be able to be called more than once. However IntoIterator::into_iter consumes self and so can be called only once.

4 Likes