67

This question pertains to a pre-release version of Rust. This younger question is similar.


I tried to print one symbol with println:

fn main() {
    println!('c');
}

But I got next error:

$ rustc pdst.rs
pdst.rs:2:16: 2:19 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:2     println!('c');
                          ^~~
error: aborting due to previous error

How do I convert char to string?

Direct typecast does not work:

let text:str = 'c';
let text:&str = 'c';

It returns:

pdst.rs:7:13: 7:16 error: bare `str` is not a type
pdst.rs:7     let text:str = 'c';
                       ^~~
pdst.rs:7:19: 7:22 error: mismatched types: expected `~str` but found `char` (expected ~str but found char)
pdst.rs:7     let text:str = 'c';
                             ^~~
pdst.rs:8:20: 8:23 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:8     let text:&str = 'c';
                                  ^~~
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Denis Kreshikhin
  • 8,856
  • 9
  • 52
  • 84

3 Answers3

85

Use char::to_string, which is from the ToString trait:

fn main() {
    let string = 'c'.to_string();
    // or
    println!("{}", 'c');
}
Kornel
  • 97,764
  • 37
  • 219
  • 309
Hubro
  • 56,214
  • 69
  • 228
  • 381
  • 2
    Yes, weirdly the docs refer to to_string() but never actually define it. – Josh Hansen Feb 14 '19 at 22:17
  • 3
    It's from the `ToString` trait, which is automatically implemented on anything that implements the `Display` trait, which includes `char`. (`impl ToString for T where T: Display + ?Sized`) This indirection, however, means that this won't show up in documentation, and is just something you have to memorize/learn. – Alex Nov 01 '19 at 04:47
23

Using .to_string() will allocate String on heap. Usually it's not any issue, but if you wish to avoid this and want to get &str slice directly, you may alternatively use

let mut tmp = [0u8; 4];
let your_string = c.encode_utf8(&mut tmp);
Evan Shaw
  • 23,839
  • 7
  • 70
  • 61
alagris
  • 1,838
  • 16
  • 31
21

You can now use c.to_string(), where c is your variable of type char.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Amandasaurus
  • 58,203
  • 71
  • 188
  • 248
  • 6
    This doesn't seem documented explicitly, but it's true because char's implement Display and Display implementations require to_string, but you wouldn't know that from the Display documentation, this is documented on the ToString trait. Which is not very good. https://doc.rust-lang.org/std/string/trait.ToString.html – Bjorn Feb 09 '17 at 23:41