73

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'; ^~~ 
0

3 Answers 3

92

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

fn main() { let string = 'c'.to_string(); // or println!("{}", 'c'); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, weirdly the docs refer to to_string() but never actually define it.
It's from the ToString trait, which is automatically implemented on anything that implements the Display trait, which includes char. (impl<T> 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.
30

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); 

3 Comments

To complete this answer and actually get the &str out, you need std::str::from_utf8(&tmp).unwrap().
@BallpointBen not really - encode_utf8 returns &mut str already.
Whoops, sorry, you're right
22

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

1 Comment

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. doc.rust-lang.org/std/string/trait.ToString.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.