如何将字符转换为字符串? [英] How can I convert char to string?
本文介绍了如何将字符转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题与 Rust 的预发布版本有关.这个年轻的问题类似.
This question pertains to a pre-release version of Rust. This younger question is similar.
我试图用 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';
它返回:
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';
^~~
推荐答案
使用 char::to_string
,即 来自 ToString
特性:
Use char::to_string
, which is from the ToString
trait:
fn main() {
let string = 'c'.to_string();
// or
println!("{}", 'c');
}
这篇关于如何将字符转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文