14

Is there a succinct way to convert a char to a String in Rust other than:

let mut s = String::new();
s.push('c');
Daniel Fath
  • 16,453
  • 7
  • 47
  • 82

2 Answers2

18

You use the to_string() method:

'c'.to_string()
tshepang
  • 12,111
  • 21
  • 91
  • 136
Steve Klabnik
  • 14,521
  • 4
  • 58
  • 99
  • 2
    Hm, that's funny. I searched Rust API for `to_string` but found no implementers that method on char. Could you post a link to it's API. For completeness sake `^_^`! – Daniel Fath Jan 18 '15 at 00:24
  • 2
    @DanielFath: you're looking for [`std::string::ToString::to_string`](http://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string), which has a blanket impl for `T: String`, which `char` implements. – DK. Jan 18 '15 at 03:21
  • 1
    Oh, so that's how it works. I thought `String` was buffer like structure, while in fact it's a trait. Hmm... – Daniel Fath Jan 18 '15 at 11:20
  • 4
    It's both: http://doc.rust-lang.org/nightly/std/string/struct.String.html and http://doc.rust-lang.org/nightly/std/fmt/trait.String.html – Steve Klabnik Jan 18 '15 at 15:47
2

Since Rust 1.46, String implements From<char>, so you can alternatively use:

String::from('c')

or, with type inference,

'c'.into()
L. F.
  • 19,445
  • 8
  • 48
  • 82