您可以使用
format!
宏将
char
转换为
String
:
fn to_ascii(i: &i32) -> String {
match *i {
x@0...127 => format!("{:?}", x as u8 as char),
_ => "".into(),
}
}
fn main() {
for x in 0x09..0x12 {
print!("{} ", to_ascii(&x));
}
println!("");
for x in 0x30..0x40 {
print!("{} ", to_ascii(&x));
}
println!("");
}
这会返回转义代码'\u{0}'
而不是缩写"NUL"
。如果您不喜欢它的外观,可以使用大量匹配或字符串数组。
实际上,您只需要重新定义33个控制字符。对于其他可打印字符,您仍然可以使用 format!
:
fn to_ascii(i: &i32) -> String {
match *i {
x@0...32 => ["NUL", "SOH", "STX", ..., "SPC"][x as usize].into(),
x@33...126 => format!("{}", x as u8 as char),
127 => "DEL".into(),
_ => "".into(),
}
}
如果想要更加 Rust 风格的写法,可以使用类似Cow
的智能指针作为返回类型:
use std::borrow::Cow;
fn to_ascii(i: &i32) -> Cow<'static, str> {
match *i {
x@0...32 => ["NUL", "SOH", "STX", ..., "SPC"][x as usize].into(),
x@32...126 => format!("{}", x as u8 as char).into(),
127 => "DEL".into(),
_ => "".into(),
}
}
关于Cow
的使用,在此处阅读更多内容。
&'static str
应该是可以的。 - user1610406