如何将值映射到 Rust 中的类型? [英] How can I map a value to a type in Rust?

查看:69
本文介绍了如何将值映射到 Rust 中的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a program which accepts a numerical type on the command line, and then calls a generic function using that type. For example, I run program thus:

my_programme u32

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

...and in my code I have:

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

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

If I want to do this for 8, 16, 32, and 64 bit integers, both signed and unsigned, that's a lot of calls to my_generic_function(). It looks messy and seems needless.

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

Can I define a map between &str or String values and type T, or write a function to return type T, so instead of the match statement, I could just write:

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

推荐答案

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

Rust doesn't keep any type information at runtime. There is a function in the standard library, std::any::type_name, which can give you the name of a type, but it's just a string and there is no way to get back into the world of types. That all happens at compile time and can't be changed later.

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

However, you can save some code with a macro:

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),
    }
}

这篇关于如何将值映射到 Rust 中的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆