Hi,
I have this kind of code:
enum MyEnum {
A,
B,
}
impl MyEnum {
pub fn as_str(&self) -> &'static str {
match self {
MyEnum::A => "A",
MyEnum::B => "B",
}
}
pub fn as_key(&self) -> &'static str {
match self {
MyEnum::A => "A=",
MyEnum::B => "B=",
}
}
}
is there a way to avoid rematching variants in as_key
as it's basically as_str()
concatenate with '='?
I've found this Concatenate two `&'static str` from 2019, so asking again in 2021 as const fn
landed, I was wondering if I was missing something.
I tried:
enum MyEnum {
A,
B,
}
impl MyEnum {
pub const fn as_str(&self) -> &'static str {
match self {
MyEnum::A => "A",
MyEnum::B => "B",
}
}
pub fn as_key(&self) -> &'static str {
concat!(self.as_str(), "=")
}
}
But even with as_str()
being const, it doesn't accept it
If your goal is just to avoid typing the mapping out twice, have you considered flipping which function calls which?
enum MyEnum {
A,
B,
}
impl MyEnum {
pub fn as_str(&self) -> &'static str {
&self.as_key()[..1]
}
pub fn as_key(&self) -> &'static str {
match self {
MyEnum::A => "A=",
MyEnum::B => "B=",
}
}
}
6 Likes
Hyeonu
June 15, 2021, 7:50am
4
const-concat
crate provides both library implementation for it AND explanation why it's wicked hard problem.
2 Likes
I think I need 17 cups of coffee to be awake enough to think of this simple solution… x)
1 Like
Note that const_concat!
does some technically UB things, such as transmuting a &[u8]
to a &str
, since str::from_utf8_unchecked
is not a const fn
yet. Using a newtype wrapper that calls the zero-cost from_utf8_unchecked
on Deref would thus be a more sound approach:
Back to the OP, performing a const
concatenation of &str
s requires a very convoluted dance between "values" and "types" which:
require macros, since actual function signatures would be unable to express such a dance (it would be dependent typing);
require const
blocks ; they are incompatible with const fn
s due to all the shenanigans involved.
On the other hand, const
truncation is indeed a way way simpler solution
4 Likes
system
Closed
September 13, 2021, 10:19am
7
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.