I'm looking for ways to declare String constants in Rust by concatenating chars.
What I would like to achieve is something like this:
{ Pascal Code }
const ESC = #27;
const RESET_PRINTER = ESC + '@';
Here's where I ended for now after few hours of research:
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);
}
Edit
Per @e-net4-stays-away-from-meta suggestion a String can easily be created from [char] by using 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);
}
chars, then collect it.&[char]without passing its size. Justfor c in cde {...}or even bettercde.into_iter().collect()Stringin Rust, since you can't allocate memory on the heap when creating a constant. Would a&strwork as well for you? Would a lazily initialized staticStringfit the bill?