Rust: Converting [char] to String

Created on 27 Feb 2015  路  4Comments  路  Source: rust-lang/rust

There should be a way to convert [char] to String. This can't be done in-place like [u8] to &str (with std::str::from_utf8) but should still be available.

Maybe something like this?

impl ToString for [char] {
    fn to_string(&self) -> String {
        let mut s = String::with_capacity(self.len()); // capacity? char != byte
        for c in self {
            s.push(c.clone());
        }
        s
    }
}

http://is.gd/neQ0XH

Most helpful comment

+1 Would be really helpful if Rust stdlib could convert between its own types.

All 4 comments

Hi, feature requests for added functionality rather than bug reports should go to https://github.com/rust-lang/rfcs/issues now, so I'm closing this.

However, given that you can collect a iterator of chars into a String, and have the size hint apply so that it allocates the right size already, I don't think this is strictly needed at this point.

It is also not clear whether ['a', 'b'].to_string() should produce "ab" or "['a', 'b']".

I see.

For future reference, the approach mentioned is array.iter().cloned().collect::<String>().

+1 Would be really helpful if Rust stdlib could convert between its own types.

UPDATE: you can now collect an iterator of chars into a string, so that's all sorted out

Was this page helpful?
0 / 5 - 0 ratings