Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a variable as the data type for a different variable?

Tags:

variables

rust

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
like image 746
Ariel Hurdle Avatar asked Sep 27 '19 17:09

Ariel Hurdle


People also ask

How do you assign a data type to a variable?

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.

Can a variable have different data types?

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 ).

Is variable and data type same?

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 ).

How do you declare a variable in a data type in Python?

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.


2 Answers

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()),
        };
    }
}
like image 182
Ultrasaurus Avatar answered Nov 15 '22 07:11

Ultrasaurus


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!

like image 35
Leo Cornelius Avatar answered Nov 15 '22 09:11

Leo Cornelius