How to convert char to string?

被刻印的时光 ゝ 提交于 2019-12-06 16:36:31

问题


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


I tried to print one symbol by io::println function

fn main() {
    io::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     io::println('c');
                          ^~~
error: aborting due to previous error

How to convert char to string?

UPDATE

Direct typecast does not work:

let text:str = 'c';
let text:&str = 'c';
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';
                              ^~~
pdst.rs:9:20: 9:23 error: mismatched types: expected `@str` but found `char` (expected @str but found char)
pdst.rs:9     let text:@str = 'c';
                              ^~~
pdst.rs:10:20: 10:23 error: mismatched types: expected `~str` but found `char` (expected ~str but found char)
pdst.rs:10     let text:~str = 'c';
                               ^~~
error: aborting due to 5 previous errors

回答1:


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

fn main() {
    io::println('c'.to_string());
}



回答2:


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



来源:https://stackoverflow.com/questions/16267578/how-to-convert-char-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!