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.