I have an array of strings like
const LANGUAGES: [&str; 3] = [
"EN",
"ES",
"DE",
];
and I would like to lowercase them at compile time. How can I do that?
I have an array of strings like
const LANGUAGES: [&str; 3] = [
"EN",
"ES",
"DE",
];
and I would like to lowercase them at compile time. How can I do that?
Using the konst
and const_str
package, we can achieve this by joining a slice into a single string, applying the convert_ascii_case
macro to lowercase it, and then splitting the string by the same delimiter into a slice
With arrays,
const SIZE: usize = 3;
const LANGUAGES: [&str; SIZE] = ["EN", "ES", "DE"];
const LOWERED: [&str; SIZE] = {
const SEPERATOR: &str = "|";
const AS_SLICE: &[&str] = &LANGUAGES;
const JOINED: &str = konst::string::str_join!(SEPERATOR, AS_SLICE);
const LOWERED_JOINED: &str = const_str::convert_ascii_case!(lower, JOINED);
const_str::split!(LOWERED_JOINED, SEPERATOR)
};
println!("{:#?}", LOWERED);
With slices,
const LANGUAGES: &[&str] = &["EN", "ES", "DE"];
const LOWERED: &[&str] = {
const SEPERATOR: &str = "|";
const JOINED: &str = konst::string::str_join!(SEPERATOR, LANGUAGES);
const LOWERED_JOINED: &str = const_str::convert_ascii_case!(lower, JOINED);
&const_str::split!(LOWERED_JOINED, SEPERATOR)
};
println!("{:#?}", LOWERED);
You may also want to look into konst
's for_each
macro and the general idea of const_eval
. But I have yet to construct a working example using that.