Tsar Buig
Tsar Buig

Reputation: 13

How to handle arrays of different array lengths depending on a condition?

I have 2 different arrays in my program:

const ARRAY_1: [u8; 2] = [0xe8, 0xe3, 0x37, 0x00];
const ARRAY_2: [u8; 4] = [0xe8, 0xe3];

I want to write something like:

if condition1 {
    let ARRAY_CHOSEN: [&[u8]; 2] = ARRAY_1;
}
else if condition2 {
    let ARRAY_CHOSEN: [&[u8]; 4] = ARRAY_2;
}

and then work with ARRAY_CHOSEN in the rest of the function... But of course it does not work because ARRAY_CHOSEN is contained in a nested scope.

How can I choose a 2-item or 4-item array depending on a condition?

Upvotes: 1

Views: 185

Answers (2)

kmdreko
kmdreko

Reputation: 60152

You could coerce them into slices, &[u8]:

const ARRAY_1: [u8; 4] = [0xe8, 0xe3, 0x37, 0x00];
const ARRAY_2: [u8; 2] = [0xe8, 0xe3];

fn main() {
    let condition1 = false;
    let condition2 = true;
    
    let arr_chosen = if condition1 {
        &ARRAY_1[..]
    } else if condition2 {
        &ARRAY_2[..]
    } else {
        &[]
    };
    
    dbg!(arr_chosen);
}
[src/main.rs:16] arr_chosen = [
    232,
    227,
]

Upvotes: 3

naiveai
naiveai

Reputation: 853

In general this is not a workable pattern in idiomatic Rust code. There is a possibility you could use const generics for this, but I'd advise against looking into those if you're a beginner since they fit in only specific use cases.

Just use a Vec which can be of any size, along with the if condition as an expression:

let chosen = if condition1 {
    vec![1, 2, 3]
} else if condition2 {
    vec![1, 2, 3, 4, 5, 6]
} else {
    // you have to provide some default here to cover
    // the case where both condition1 and condition2 are false
    // or you can panic but that is inadvisable
    vec![1, 2, 3]
}

Upvotes: 0

Related Questions