Create struct instance using string name aka "Reflection"

Hello,
I'm new to rust and started learning few days back. I have a struct "Node", by using traits I have created near about 50+ other structs. Now in order to use them first I have to import them. For example:

use core::node::A;
use core::node::B;
...

I can create an instance at compile time using this syntax:
let mut a= A::new();
But I'm looking for a way to dynamically create instances at run time using string. Some thing like:
let mut a = createInstance(&"A")::new();
or much better if I can use full path
let mut a = createInstance(&"core::node::A")::new();

Cheers

I don't think that can be done, without macros atleast.
And even then, I don't think it will be at runtime (dynamically) - because macros are expanded out to regular Rust code at compile time.
Rust doesn't have reflection as far as I know - neither does C++ or C.

createInstance returns different typed objects based on the value of the &str right ?

What is the compile time type signature of createInstance ?

I just created as an example reference. I myself don't know how to implement such functionality. I'm also open for any other hackish way to implement such requirement.

If they all implement one trait a trait object might be what you want.

fn create_instance(name: &str) -> Box<dyn SomeTrait> {
    match name {
        "A" => Box::new(A::new()),
        // ...
    }
}

I think you should tell us more about why you want this though.

2 Likes

The application is based on DAG solver. All the 50+ nodes are created using "Node" trait. The data is loaded from an external file and I have to create nodes at runtime as defined in data file.

It looks like you are trying to deserialize an enum. Model your nodes as an enum (and maybe use Serde for easily deserializing them). There is no way to summon dynamic types out of thin air based on their name.

2 Likes

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.