Can I convert a String to a Type name?

Can I convert a String to a Type name, like "i32" => i32, it is expected work like this:

macro convert_string_to_type {
    ($my_string: expr) {
        // eval(expr)

fn Foo<T>() {}

Foo::<convert_string_to_type!("i32")>() <=> Foo::<i32>()

Foo::<convert_string_to_type!("f32")>() <=> Foo::<f32>()

What do you want to achieve? Can you describe your goal?

If you know the type you want, why don't you write it directly?

For example, I have a long Vector of String like vec!["i32", "f32", "type1", "type2"...]. I need that each element of the vector call Foo like above.

You could do this:

match type_name {
    "i32" => Foo::<i32>::(),
    "f32" => Foo::<f32>::(),
    "type1" => Foo::<type1>::(),

It is not otherwise possible.


That's just not possible. Generics need to be resolved at compile time. You can have a fixed list of types, write a macro to generate all the possible function calls. But not a runtime list.


That work fine. But if the Vector<String> is generated by some generic type, I can not write all the possilbe type on the match arm, what should I do?

It is not possible to dynamically generate new, arbitrary instantiations of generics at runtime.

1 Like

It's fundamentally not possible. Change your code in some way, e.g. maybe you can use trait objects instead of strings?


Yes, I tried to make the Vector<Box<dyn MyTrait>>, but I also need to serialize the vector to a local file, which I will deserialize later.
So I have to use typetag to make the Box<dyn MyTrait> to be able to serialized and deserialzed. But the trait MyTrait implement by like impl<T: MyTrait<Type1>> My<Type2> for MyStruct<T>, which can not be use #[typetag::serde].
So I have to change the trait MyTrait to have no generic style, and this lead to using Box<dyn MyTrait> everywhere. But I need MyStruct<T> can be accessed to its field by like my_struct.0 or my_struct.0.0, and Box<dyn MyTrait> make this impossible.

If you want to be able to serialize it, you'll probably need to have a complete list of all of the types in your program somewhere, unfortunately.


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.