59

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,030
  • 21
  • 100
  • 124
Denis Kreshikhin
  • 7,996
  • 8
  • 48
  • 81

3 Answers3

81

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

fn main() {
    let string = 'c'.to_string();
    // or
    println!("{}", 'c');
}
Kornel
  • 94,425
  • 32
  • 211
  • 296
Hubro
  • 52,462
  • 63
  • 210
  • 362
  • 2
    Yes, weirdly the docs refer to to_string() but never actually define it. – Josh Hansen Feb 14 '19 at 22:17
  • 2
    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
21

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

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Amandasaurus
  • 54,108
  • 68
  • 182
  • 239
  • 5
    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
10

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
  • 22,406
  • 5
  • 67
  • 60
alagris
  • 1,044
  • 9
  • 20