如何在 Rust 中打印变量的类型? [英] How do I print the type of a variable in Rust?

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

问题描述

我有以下几点:

let mut my_number = 32.90;

如何打印my_number的类型?

使用 typetype_of 不起作用.还有其他方法可以打印号码的类型吗?

Using type and type_of did not work. Is there another way I can print the number's type?

推荐答案

如果你只是想找出一个变量的类型并且愿意在编译时这样做,你可以导致错误并让编译器捡起来.

If you merely wish to find out the type of a variable and are willing to do it at compile time, you can cause an error and get the compiler to pick it up.

例如,将变量设置为不起作用的类型:

let mut my_number: () = 32.90;
// let () = x; would work too

error[E0308]: mismatched types
 --> src/main.rs:2:29
  |
2 |     let mut my_number: () = 32.90;
  |                             ^^^^^ expected (), found floating-point number
  |
  = note: expected type `()`
             found type `{float}`

调用无效方法:

let mut my_number = 32.90;
my_number.what_is_this();

error[E0599]: no method named `what_is_this` found for type `{float}` in the current scope
 --> src/main.rs:3:15
  |
3 |     my_number.what_is_this();
  |               ^^^^^^^^^^^^

或者 访问无效字段:

let mut my_number = 32.90;
my_number.what_is_this

error[E0610]: `{float}` is a primitive type and therefore doesn't have fields
 --> src/main.rs:3:15
  |
3 |     my_number.what_is_this
  |               ^^^^^^^^^^^^

这些揭示了类型,在这种情况下实际上并没有完全解析.在第一个示例中称为浮点变量",在所有三个示例中都称为{float}";这是一个部分解析的类型,最终可能是 f32f64,具体取决于您如何使用它.{float}"不是合法的类型名称,它是一个占位符,意思是我不完全确定这是什么",但它一个浮点数.对于浮点变量,如果不对其进行约束,则默认为 f64¹.(未限定的整数文字将默认为 i32.)

These reveal the type, which in this case is actually not fully resolved. It’s called "floating-point variable" in the first example, and "{float}" in all three examples; this is a partially resolved type which could end up f32 or f64, depending on how you use it. "{float}" is not a legal type name, it’s a placeholder meaning "I’m not completely sure what this is", but it is a floating-point number. In the case of floating-point variables, if you don't constrain it, it will default to f64¹. (An unqualified integer literal will default to i32.)

另见:

¹ 可能仍然有一些方法让编译器无法在 f32f64 之间做出决定;我不确定.它曾经像 32.90.eq(&32.90) 一样简单,但现在将两者都视为 f64 并且愉快地进行,所以我不知道.

¹ There may still be ways of baffling the compiler so that it can’t decide between f32 and f64; I’m not sure. It used to be as simple as 32.90.eq(&32.90), but that treats both as f64 now and chugs along happily, so I don’t know.

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

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