HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How can I convert char to string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howconvertcancharstring

Problem

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

Solution

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

fn main() {
    let string = 'c'.to_string();
    // or
    println!("{}", 'c');
}

Code Snippets

fn main() {
    let string = 'c'.to_string();
    // or
    println!("{}", 'c');
}

Context

Stack Overflow Q#16267578, score: 94

Revisions (0)

No revisions yet.