So long as you don't need to return the &str
from the function, you can completely avoid heap allocation using char::encode_utf8
:
const SP_KEY_1: u8 = 0;
const SP_KEY_2: u8 = 1;
const SP_KEY_3: u8 = 2;
const SP_KEY_4: u8 = 3;
const SP_KEY_5: u8 = 4;
const SP_KEY_6: u8 = 5;
fn main() {
let k = 42u8;
let mut tmp = [0; 4];
let s = match k {
SP_KEY_1 => "KEY_1",
SP_KEY_2 => "KEY_2",
SP_KEY_3 => "KEY_3",
SP_KEY_4 => "KEY_4",
SP_KEY_5 => "KEY_5",
SP_KEY_6 => "KEY_6",
_ => (k as char).encode_utf8(&mut tmp),
};
println!("{}", s);
}
This could be paired with a closure if you needed more control:
fn adapt<F, B>(k: u8, f: F) -> B
where
for<'a> F: FnOnce(&'a str) -> B,
{
let mut tmp = [0; 4];
let s = match k {
SP_KEY_1 => "KEY_1",
SP_KEY_2 => "KEY_2",
SP_KEY_3 => "KEY_3",
SP_KEY_4 => "KEY_4",
SP_KEY_5 => "KEY_5",
SP_KEY_6 => "KEY_6",
_ => (k as char).encode_utf8(&mut tmp),
};
f(s)
}
fn main() {
adapt(0, |s| println!("{}", s));
let owned = adapt(0, |s| s.to_owned());
}
Or stored in a struct to provide a little bit of abstraction:
#[derive(Debug, Default)]
struct Foo {
tmp: [u8; 4],
}
impl Foo {
fn adapt(&mut self, k: u8) -> &str {
match k {
SP_KEY_1 => "KEY_1",
SP_KEY_2 => "KEY_2",
SP_KEY_3 => "KEY_3",
SP_KEY_4 => "KEY_4",
SP_KEY_5 => "KEY_5",
SP_KEY_6 => "KEY_6",
_ => (k as char).encode_utf8(&mut self.tmp),
}
}
}
fn main() {
let mut foo = Foo::default();
{
let s = foo.adapt(0);
}
{
let s = foo.adapt(42);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…