1. as
运算符
as
运算符有点像 C 中的强制类型转换,区别在于,它只能用于原始类型(i32
、i64
、f32
、f64
、 u8
、 u32
、 char
等类型),并且它是安全的。
例
在 Rust 中,不同的数值类型是不能进行隐式转换的,比如:
let b: i64 = 1i32;
会出现编译错误,提示无法进行类型转换。
error[E0308]: mismatched types
--> src\main.rs:2:18
|
2 | let b: i64 = 1i32;
| ^^^^ expected i64, found i32
help: change the type of the numeric literal from `i32` to `i64`
这时可以使用as 进行转换。
let b: i64 = 1i32 as i64;
为什么它是安全的?
尝试以下代码:
let b = 1i32 as char;
编译器错误:
error[E0604]: only `u8` can be cast as `char`, not `i32` --> src\main.rs:2:13 | 2 | let b = 1i32 as char; | ^^^^^^^^^^^^
可见在不相关的类型之间,Rust 会拒绝转换,这也避免了运行时错误。
2. Trait From<T>
和 Into<T>
上文说到,as
运算符之能在原始类型之间进行转换,那么对于 Struct 和 Enum 这样的类型该如何进行转换呢? 这就是我们这节的内容