Function or macro that convert datatype in runtime

tried 1

let value: &str = path_split[i];

const split_type: &str = match param_split.next() {
    Some(x) => x,
    _ => "String",
};

let parsed_value;

if split_type == "String" {
    parsed_value = value.to_owned();
} else {
    parsed_value = value.parse::<split_type>();
}

tried 2 with macro

#[macro_export]
macro_rules! type_conversion {
    ($ty:ty, $str:expr) => {{
        let str: String = String::from($str);
        match str.parse::<$ty>() {
            Ok(x) => x.to_owned(),
            _ => "".to_owned(),
        }
    }};
}

usage
type_conversion!("u32", "some string 123")

There's no straightforward way to do that. The whole approach is for dynamically-typed programs, and not appropriate for Rust. Except of very limited cases, types and their names don't even exist in Rust programs at run time.

The FromStr trait has to know the target type at compilation time. You can make something like a match or enum that lists a limited fixed set of types that you support, but it can't be open-ended at run time.

Another way is to have types that implement reflection-like interface and are registered for name-based lookup at run time: bevy_reflect - Rust

1 Like

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.