Is it possible to initialize array elements out of order?

Given the following code:

trait FooTrait {}

struct Foo {}
impl FooTrait for Foo {}

struct Bar {}
impl FooTrait for Bar {}

struct FooBar {}
impl FooTrait for FooBar {}

struct BarFoo {}
impl FooTrait for BarFoo {}

const TOTAL_FOO : usize = 4;

enum FooEnum {
    Foo = 0,
    Bar = 1,
    FooBar = 2,
    BarFoo = 3,

I have an array [Box<dyn FooTrait>; TOTAL_FOO] and an enum FooEnum which values map exactly where each concrete implementation of FooTrait is. The problem that I have is when initializing this array:

let array: [Box<dyn FooTrait>; TOTAL_FOO] = [
    Box::new(Foo {}) as Box<dyn FooTrait>, // since FooEnum::Foo == 0
    Box::new(Bar {}) as Box<dyn FooTrait>, // since FooEnum::Bar == 1
    .... // Then FooEnum::FooBar (==2) and FooEnum::BarFoo (==3)

But what if FooEnum::Foo value changes to 1 and FooEnum::Bar changes to 0? The initialized array would be wrong and if I try to get my_array[FooEnum::Foo as usize] I'd end up with Bar. Is there anything like the following?

let array: [Box<dyn FooTrait>; TOTAL_FOO] = [
    // The values could change but the array would be initialized correctly
    [FooEnum::Foo as usize] = Box::new(Foo {}) as Box<dyn FooTrait>,
    [FooEnum::Bar as usize] = Box::new(Bar {}) as Box<dyn FooTrait>,
    .... // The order no longer matters

Are there any alternatives that require minimum code refactoring? I do know about enum_map, but I'm trying to avoid adding more dependencies to the project.

I'm also trying to avoid having to having to declare the array and then setting each value individually because this array might get declared as const in a global scope.

If it contains Box, it cannot be const.

If it can be const, you can make a const fn and build it via array indexing, and that works fine in a const context.

It looks like you want to avoid declaring the order of your enum in multiple places. I don't think there is a way to do what you want to do unless you write a macro.

Take a look at enum_dispatch to get rid of your Boxes.

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.