如何将char转换为字符串?

时间:2013-04-28 20:38:32

标签: rust rust-obsolete

  

此问题适用于Rust的预发行版本   This younger Question类似。


我尝试按io::println功能

打印一个符号
fn main() {
    io::println('c');
}

但我得到了下一个错误:

$ 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

如何将char转换为字符串?

更新

直接类型转换不起作用:

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

它返回:

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

3 个答案:

答案 0 :(得分:32)

使用char::to_stringstrangely undocumented

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

答案 1 :(得分:15)

您现在可以使用c.to_string(),其中cchar类型的变量。

答案 2 :(得分:3)

使用 .to_string() 将在堆上分配 String。通常这没什么问题,但如果你想避免这种情况并想直接获得 &str 切片,你也可以使用

let mut tmp = [0u8; 4];
let your_string = c.encode_utf8(&mut tmp));