Home > Software design >  Rust - Different array length depending on condition
Rust - Different array length depending on condition

Time:12-05

a newbie question in Rust but I've been banging my head on the wall for 2 hours...

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 {} !

--> How can I do that ? Choose a 2 items array or a 4 items array depending on condition ?

Thanks a lot guys

CodePudding user response:

Depending how you intend to use the array later, you can coerce them into slices (type &[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,
]

CodePudding user response:

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]
}
  • Related