Den*_*hin 29 rust rust-obsolete
此问题适用于Rust的预发布版本.
这个年轻的问题很相似.
我试图按io::println
功能打印一个符号
fn main() {
io::println('c');
}
Run Code Online (Sandbox Code Playgroud)
但我得到了下一个错误:
$ 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
Run Code Online (Sandbox Code Playgroud)
如何将char转换为字符串?
UPDATE
直接类型转换不起作用:
let text:str = 'c';
let text:&str = 'c';
let text:@str = 'c';
let text:~str = 'c';
Run Code Online (Sandbox Code Playgroud)
它返回:
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
Run Code Online (Sandbox Code Playgroud)
Hub*_*bro 36
使用char::to_string
,这是奇怪的未记录:
fn main() {
io::println('c'.to_string());
}
Run Code Online (Sandbox Code Playgroud)
Ror*_*ory 17
您现在可以使用c.to_string()
,c
您的类型变量在哪里char
.
使用.to_string()
将String
在堆上分配。通常这不是任何问题,但如果您想避免这种情况并想&str
直接获取切片,您也可以使用
let mut tmp = [0u8; 4];
let your_string = c.encode_utf8(&mut tmp));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19718 次 |
最近记录: |