Hello!
I am writing a very simple message dispatch function, which I've mocked up in playground below. I am referencing message names imported from bindgen, which come as references to const arrays. I'd like to use these constants in a match
in order to branch to the right handler. However, the comparisons aren't satisfying the compiler.
Is there a pretty way to make this work? I know I can do bar_name if bar_name == BAR_NAME =>
inside the match in order to get what I want, but it's a bit wordy, especially compared to the brevity of FOO_NAME
below.
Of course if I have to spell it out for the compiler, I will do it that way. But a pretty way forward would be much appreciated!
const FOO_NAME: &[u8] = b"foo";
const BAR_NAME: &[u8; 3] = b"bar"; // this is the form in which I have the constants
fn handle_msg(name: &[u8]) {
match name {
FOO_NAME => println!("got foo"), // this works
BAR_NAME => println!("got bar"), // this fails to compile
_ => println!("got unknown msg"),
}
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:7:9
|
2 | const BAR_NAME: &[u8; 3] = b"bar";
| ------------------------ constant defined here
...
5 | match name {
| ---- this expression has type `&[u8]`
6 | FOO_NAME => println!("got foo"),
7 | BAR_NAME => println!("got bar"),
| ^^^^^^^^
| |
| expected `&[u8]`, found `&[u8; 3]`
| `BAR_NAME` is interpreted as a constant, not a new binding
| help: introduce a new binding instead: `other_bar_name`
|
= note: expected reference `&[u8]`
found reference `&'static [u8; 3]`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error