1

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?

xamgore
  • 1,723
  • 1
  • 15
  • 30
Iter Ator
  • 8,226
  • 20
  • 73
  • 164

1 Answers1

1

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.

pub mod group {
    pub struct MyStruct {
        // ...
    }

    pub const Instance1: MyStruct = MyStruct {};
    
    pub const Instance2: MyStruct = MyStruct {};
    
    pub const Instance3: MyStruct = MyStruct {};
}

fn main() {
    let instance1 = group::Instance1;
    let instance2 = group::Instance2;
    // ...
}

Playground. If you want to modify them, you can use static with unsafe updates. You may implement FromStr trait for MyStruct, if you need conversions from strings.

xamgore
  • 1,723
  • 1
  • 15
  • 30