Question about dynamic variable creation

Given some type, such as String, is it possible to store the Type in a collection such as a HashMap for the purpose of retrieving it later to create a new instance of String?

Something like:

let string = String::type;
let mut types = HashMap::<String, Type>::new();
types.insert("string", string);

// ... in another place of the code

let string: String = types.get("string")?::new();

For reference, I'm thinking about this in terms of a dependency injection framework and what that might look like in a Rust world. I haven't taken a look at Crates yet to avoid spoilers :slight_smile:

Not types themselves, but you could store type constructor functions as Any:

let mut types = HashMap::<String, Box<dyn Any>>::new();
let string_new = Box::new(String::new);
types.insert("string".to_string(), string_new);

// ...

let string_new: &fn() -> String = types.get("string")?.downcast_ref()?;
let string = string_new();

Very cool! Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.