Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert iterator of chars to String?

Tags:

rust

I need something like .collect() but which will produce String instead of container of chars, i.e. I need an inverse of chars(). I cannot find anything suitable in the documentation. Of course I can implement such a function myself but I'm sure there must be standard solution to this problem.

I'm using stable Rust.

like image 554
Simon Avatar asked Jun 09 '15 20:06

Simon


People also ask

How do you convert a vector character to a string in Rust?

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


1 Answers

.collect() is generic in what collection it produces, and it can produce the String for you!

let s = "abc".chars().collect::<String>(); 

The trait FromIterator determines which elements you can collect into which kind of collection, and among the implementors you can find String twice:

impl FromIterator<char> for String impl<'a> FromIterator<&'a str> for String 

Both iterators of char and of &str can be collected to String.

like image 158
bluss Avatar answered Sep 19 '22 15:09

bluss