How to convert iterator of chars to String?

前端 未结 1 902
旧巷少年郎
旧巷少年郎 2021-02-11 18:22

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

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-11 18:49

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

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

    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 for String
    impl<'a> FromIterator<&'a str> for String
    

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

    0 讨论(0)
提交回复
热议问题