Pattern Match Const Array of Slices

I'm relatively new to Rust language and trying to do something like:

pub const ARR_SIZE: usize = 3;
fn main() {
    pub const ARR: [&str; ARR_SIZE] = [
        "Does",
        "This",
        "Work"
    ];

    println!("{}",ARR[0]);
    assert_eq!("Does", ARR[0]); // This does work

    let k = format!("{}", ARR[0]);
    println!("{}",k);
    assert_eq!(k, ARR[0].); // This does work

    let p = "Does";
    
    match p {
        ARR[0] => true, // This does not work; does not compile.
        _ => false
    };
}

The intent is to pattern match the slices in ARR with values p that are passed in.
Is there a syntax I'm missing for destructuring const arrays? Is there a reason this would cause problems?

The direct way would be inline_const_pat - The Rust Unstable Book, but that's currently nightly-only.

So you'd need to do something like

const ARR0: &str = ARR[0];
match p {
    ARR0 => true, // Now it's a const so this works.
    _ => false
};

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=13e473fe63e881217d86335e81932b41

2 Likes

Thanks for the quick reply. I'm not ready to dip into the nightly builds so I'll probably do something like you suggested above.

1 Like

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.