How to convert Vec<char> to a string

StringRust

String Problem Overview


How to convert Vec<char> to string form so that I can print it?

String Solutions


Solution 1 - String

Use collect() on an iterator:

let v = vec!['a', 'b', 'c', 'd'];
let s: String = v.into_iter().collect();
println!("{}", s);

The original vector will be consumed. If you need to keep it, use v.iter():

let s: String = v.iter().collect();

There is no more direct way because char is a 32-bit Unicode scalar value, and strings in Rust are sequences of bytes (u8) representing text in UTF-8 encoding. They do not map directly to sequences of chars.

Solution 2 - String

Here is a more readable version that consumes the vector:

use std::iter::FromIterator;

fn main() {
    let v = vec!['a', 'b', 'c', 'd'];
    let s = String::from_iter(v);
    // vs
    let s: String = v.into_iter().collect();
}

Note that collect is implemented with a call to FromIterator::from_iter:

fn collect<B: FromIterator<Self::Item>>(self) -> B
where
    Self: Sized,
{
    FromIterator::from_iter(self)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3596561View Question on Stackoverflow
Solution 1 - StringVladimir MatveevView Answer on Stackoverflow
Solution 2 - StringmalbarboView Answer on Stackoverflow