我正在寻找通过串联String
来在Rust中声明char
常量的方法。
我想要实现的是这样的:
{ Pascal Code }
const ESC = #27;
const RESET_PRINTER = ESC + '@';
经过几个小时的研究,这是我现在结束的地方:const ESC: char = '\u{001b}';
const RESET_PRINTER_ARR: [char; 2] = [ESC, '@'];
const RESET_PRINTER_STR: &str = "\u{001b}@"; // ESC + '@' ?
fn cde_str(cde: &[char], len: usize) -> String {
let mut s = String::from("");
for i in 0..len {
s.push(cde[i]);
}
s
}
fn main() {
let r1 = cde_str(&RESET_PRINTER_ARR, RESET_PRINTER_ARR.len());
println!("{}", r1);
let r2 = String::from(RESET_PRINTER_STR);
println!("{}", r2);
}
Playground link编辑
根据@e-net4-stays-away-from-meta的建议,可以使用
String
从[char]
轻松创建String::from_iter()
:use std::iter::FromIterator;
const ESC: char = '\u{001b}';
const RESET_PRINTER_ARR: [char; 2] = [ESC, '@'];
fn main() {
let r0 = String::from_iter(&RESET_PRINTER_ARR);
println!("{}", r0);
}
最佳答案
看起来这些是要发送给打印机的转义序列,并且这种打印机可能自然无法在Unicode中工作。我会让他们成为一个字节字符串。
对我来说,用Rust编写它的自然方法是这样的:
const RESET_PRINTER: &[u8] = b"\x1b@";
// other examples
const TERM_BOLD: &[u8] = b"\x1b[1m";
const TERM_UNDERLINE: &[u8] = b"\x1b[4m";
如果要生成很多它们,或者它们很长,则可以使用write a macro生成字节字符串文字。但是,除非有明确的需要,否则我将倾向于不执行该宏:在单个 crate 中,具有重复性的简单直线代码通常比要求读者考虑宏的工作方式更具可维护性。
关于rust - 在Rust中使用char常量声明String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63377865/