generics - 如何将值映射到 Rust 中的类型?

标签 generics types rust traits

我正在编写一个程序,该程序在命令行上接受数字类型,然后使用该类型调用通用函数。例如,我这样运行程序:

my_programme u32

...在我的代码中我有:

match cli_type
{
   "u32" =>
   {
       my_generic_function::<u32>(args);
   },
   "u16" =>
   ...

如果我想对 8、16、32 和 64 位整数(有符号和无符号)执行此操作,则需要多次调用 my_generic_function()。它看起来很乱而且似乎没有必要。

我可以在 &strString 值和类型 T 之间定义一个映射,或者编写一个函数来返回类型 T,所以我可以这样写:

my_generic_function::<get_type(cli_type)>(args);

最佳答案

Rust 在运行时不保留任何类型信息。标准库中有一个函数,std::any::type_name ,它可以给你一个类型的名称,但它只是一个字符串,没有办法回到类型的世界。这一切都发生在编译时,以后无法更改。

但是,您可以使用宏保存一些代码:

macro_rules! make_call_typed {
   ($($t: ty),*) => {
       fn call_typed(input: &str, args: &str) {
           match input {
               $(
                   stringify!($t) => {
                       my_generic_function::<$t>(args);
                   }
               ),*
               other => panic!("unexpected type: {}", other)
           }
        }
    }
}

当你这样调用它时:

make_call_typed!(u32, u16, i32, i16);

它将生成如下代码:

fn call_typed(input: &str, args: &str) {
    match input {
        "u32" => {
            my_generic_function::<u32>(args);
        }
        "u16" => {
            my_generic_function::<u16>(args);
        }
        "i32" => {
            my_generic_function::<i32>(args);
        }
        "i16" => {
            my_generic_function::<i16>(args);
        }
        other => panic!("unexpected type: {}", other),
    }
}

关于generics - 如何将值映射到 Rust 中的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68216369/

相关文章:

haskell - 一元类型混淆

C : Function parameter with undefined type parameters

rust - 将方法从特征实现移动到特征定义时出现不匹配类型错误

Rust:使用通用特征作为特征参数

generics - 为什么移动闭包不会捕获具有通用类型的值?

c# - 模拟是运算符(operator)

java - Void 方法缺少返回值?

types - 将类型转换为字符串

rust - 将浮点和从 Python 重写为 Rust

c# - 如何通过代码泛化分析数据?