How do I use a variable as the data type for a different variable?
As long as you know all of your types at compile time, it is possible to transform unstructured data into typed data based on some value in the data. This is exactly what is done by the popular serde crate
Without knowing the use case, it's difficult to address the question precisely, yet the code below gives two examples about how to accomplish type-mapping using an enum (though match could be used to map any data to any type that is known at compile time).
enum VarType {
A(String),
B(String),
Unknown(String),
}
fn main() {
let _var1 = VarType::A("abc".to_string());
let _var2 = VarType::B("xyz".to_string());
let data = vec![("a", "abc"), ("b", "xyz")];
for item in data {
let (data_type, value) = item;
match data_type {
"a" => VarType::A(value.to_string()),
"b" => VarType::B(value.to_string()),
_ => VarType::Unknown(value.to_string()),
};
}
}
As Isak van Bakel, most said rust is static. However, if you have a list of all the possible structures, you can. (assuming your using serde here!). There is currently a interesting question discussing polymorphic de-serialisation here, i suggest you take a look as it may help!