2013-04-28 149 views
16

This Question pertains to a pre-release version of Rust.
This younger Question is similar.如何将char转换为字符串?


我试图通过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 

如何字符转换为字符串?

UPDATE

直接类型转换不起作用:

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 

回答

14

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

+2

这似乎没有明确说明,但它是真实的,因为char的实现显示和显示实现需要to_string,但是您不会从Display文档知道这一点,这是记录在ToString特征上的。这不是很好。 https://doc.rust-lang.org/std/string/trait.ToString.html – 2017-02-09 23:41:22