rusttypestypingstring-constant

When defining a new variable, how to decide its type according to the string value of a constant (or other variable)?


I want to be able to decide the type of a new variable by the name of a previous variable, for example:

//the text of this variable must determine the type of the second variable
const TYPE_NAME: &str = "u16";
fn main() {
    //if this worked, this second_variable must be of type u16, which is the string text indicated in type_name
    let second_variable: {TYPE_NAME} = 777;
    println!("TYPE_NAME: {}, second_variable: {}", TYPE_NAME, second_variable);
}

However this code is incorrect, and I get this error:

error[E0573]: expected type, found constant `TYPE_NAME`
 --> test.rs:5:23
  |
5 |     let second_variable: TYPE_NAME = 777;
  |                          ^^^^^^^^^ not a type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0573`.

How can I do this? Is there some other way to do it besides a match loop?

The detail is that this must be used in multiple parts of the code, and will ideally be defined with a constant, so, for example, I can in one line change the maximum value of my numeric variables from u16 to u32 or turn them into floats f64, or something like that.


Solution

  • You cannot declare a type from a string, but what you want is a type alias:

    type Type = u16;
    
    let second_variable: Type = 777;