I have $($item:ident),*
as input for my macro_rules!
and want generate match
statement for function:
fn match_x(bytes: &[u8]) -> Foo {
match bytes {
b"One" => Foo::One,
b"Two" => Foo::Two,
_ => Foo::Unknown,
}
}
But I can not find way to solve it, I tried this:
match bytes {
$(stringify!($item).as_bytes() => Foo::$item,)*
_ => Foo::Unknown,
}
but compiler do not like .as_bytes()
call in match.
That is rather strange because of as_bytes
is const function.
I also tried b stringify!($item)
and bstringify!($item)
,
but all this is wrong conceptions.
Any way to use get bytes from ident and compiler happy?
$(
#[allow(nonstandard_style)]
const $item: &[u8] = stringify!($item).as_bytes();
)*
match bytes {
$(
| $item => Foo::$item,
)*
| _ => Foo::Unknown,
}
More generally, bstringify!
can be trivially implemented with a procedural macro.
So that's what I've done: feel free to use it!
2 Likes
Thank you for answer, I don't even think into this direction (defining const).
If I remember correctly some time ago Rust compiler interpret named constant in match as variable/alias declaration,
like:
match x {
y => { (1) }
}
inside (1) y is new variable equal to x.
But looks like this was fixed some time ago?
system
Closed
4
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.