If I have the data type of something stored in the variable data_type
, how can I create a new variable with the data type defined in this variable?
For example:
struct a {
var: String,
}
struct b {
var: String,
}
let var_type = "a";
let variable: var_type { var: "abc" }; // creates struct var_type
To assign value to a variable equal sign ( = ) is used. The = sign is also known as the assignment operator. x = 100 # x is integer pi = 3.14 # pi is float empname = "python is great" # empname is string a = b = c = 100 # this statement assign 100 to c, b and a.
How can a variable have 2 data types? It cannot. An object has one type. A single type can represent values of different types (unions, std::variant ).
All variables in the Java language must have a data type. A variable's type determines the values that the variable can have and the operations that can be performed on it. For example, the declaration int count declares that count is an integer ( int ).
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With