Pattern match beginning of byte slice against byte string literal

I've got a slice of bytes and I want to be able to do different things depending on the bytes at the start of the slice. The obvious way to do this would be a match statement with subslice pattern matching. I've gotten that to work by manually creating the byte array, but that's very verbose and tedious to do. I've tried making it work with byte string literals, but haven't found a way to make that work with subslices.

let slice: &[u8] = b"FooBar";
match slice
{
    [b'F', b'o', b'o', ..] => , //Works, but is terrible
    b"Foo" => //Doesn't work
    // b"Foo".. => // Would like something like this to work
}

Here are two options:

let slice: &[u8] = b"FooBar";

if slice.starts_with(b"Foo") {
    // ...
} else if slice.starts_with(b"Bar") {
    // ...
}
let slice: &[u8] = b"FooBar";

match slice {
    s if s.starts_with(b"Foo") => {
        // ...
    }
    s if s.starts_with(b"Bar") => {
        // ...
    }
    _ => {}
}

Just as an idea, if the number of bytes you want to match is the same for all arms you can do this

let slice: &[u8] = b"FooBar";
match &slice[..3] {
    b"Bar" => "hi",
    b"Foo" => "hello",
    _ => "bonjour",
};

Or

match slice.split_at(3) {
    (b"Bar", rest) => println!("hi, bytes {rest:?}"),
    (b"Foo", rest) => println!("hello, bytes {rest:?}"),
    _ => println!("bonjour"),
};

Or, for a bit less repetition:

let (prefix, rest) = slice.split_at(3);
match prefix { 
    b"Bar" => println!("hi, bytes {rest:?}"),
    /* ... */
}

Unfortunately, they're not.

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.