Iterator of char into String?

Right. I've never even used this impl, but my first thought upon seeing the question "I have an Iterator of X and need a Y" was to look at the FromIterator impls of Y.

If that impl didn't exist, I'd then look for the following:

  • Other FromIterator<X> impls for String to see if any of those X can easily be produced from char (and then I would call map before .collect()).
  • impl FromIterator<char> for Vec<u8>. If this existed I would use String::from_utf8(iterator.collect()).
  • impl Add<char> for String. If this existed, I would use .fold(String::new(), |s, c| s + c)
  • methods of char to see if there's anything that lets you obtain the UTF8 bytes. Indeed, there is encode_utf8, which even gives a &mut str, so one can write
    .fold(String::new(), |s, c| {
        let mut buffer = [u8; 4];
        s += &*c.encode_utf8(&mut buffer);
        s
    })
    
  • idly check the inherent methods of String for whatever pops out at me

and if I could still find nothing after all of that I'd slam my head into a wall somewhere.

3 Likes