I would like to store many predefined instances of a struct as constants and group them in a way that I am able to reference them by name.
I could achieve it like this:
use std::collections::HashMap;
struct MyStruct {
// ...
}
const INSTANCES: HashMap<&str, MyStruct> = [
("Instance1", MyStruct {
// fields...
}),
("Instance2", MyStruct {
// fields...
}),
("Instance3", MyStruct {
// fields...
}),
// Add more instances as needed
].iter().cloned().collect();
fn main() {
let instance = INSTANCES.get("Instance1");
// ...
}
Or this:
struct MyStruct {
// ...
}
enum MyStructInstance {
Instance1,
Instance2,
Instance3,
// Add more instances as needed
}
impl MyStructInstance {
fn get_instance(&self) -> MyStruct {
match self {
MyStructInstance::Instance1 => MyStruct {
// fields...
},
MyStructInstance::Instance2 => MyStruct {
// fields...
},
MyStructInstance::Instance3 => MyStruct {
// fields...
},
// ...
}
}
}
fn main() {
let instance1 = MyStructInstance::Instance1.get_instance();
// ...
}
But it does not seem well formed. What is the standard way for storing a named list of predefined instances?