Rust 编程中的强制转换
在 Rust 中只允许强制转换或显式转换,编译器不会自动进行隐式转换。众所周知,在许多情况下,隐式转换会导致数据丢失,这是一个严重的问题。
在不同类型之间转换的规则与 C 语言非常相似。但是,在 Rust 中,当我们要从一种类型转换为另一种类型时,我们使用 as 关键字。
示例
考虑以下示例
// Suppress all warnings from casts which overflow. #![allow(overflowing_literals)] fn main() { let decimal = 65.43_f32; // Error! No implicit conversion // let integer: u8 = decimal; // FIXME ^ Comment out this line // Explicit conversion let integer = decimal as u8; let character = integer as char; println!("Casting: {} -> {} -> {}", decimal, integer, character); }
在上面的代码示例中,我们尝试将一个 float32 值转换为一个整数,然后将该整数转换为一个 char,最后将它们打印到终端。
输出
Casting: 65.43 -> 65 -> A
如果我们删除对隐式转换的注释,则编译器将抛出一个错误。
示例
考虑下面显示的更新后的代码
// Suppress all warnings from casts which overflow. #![allow(overflowing_literals)] fn main() { let decimal = 65.43_f32; // Error! No implicit conversion let integer: u8 = decimal; // FIXME ^ Comment out this line // Explicit conversion let integer = decimal as u8; let character = integer as char; println!("Casting: {} -> {} -> {}", decimal, integer, character); }
输出
error[E0308]: mismatched types --> src/main.rs:8:23 | 8| let integer: u8 = decimal; | -- ^^^^^^^ expected `u8`, found `f32` | | | expected due to this
从 Rust 1.45 开始,当我们将浮点数转换为整数时,‘as’ 关键字还会执行 饱和转换。
示例
考虑下面显示的代码作为一个示例
// Suppress all warnings from casts which overflow. #![allow(overflowing_literals)] fn main() { // 300.0 is 255 println!("301.0 is {}", 301.0_f32 as u8); // -100.0 as u8 is 0 println!("-101.0 as u8 is {}", -101.0_f32 as u8); // nan as u8 is 0 println!("nan as u8 is {}", f32::NAN as u8); }
输出
301.0 is 255 -101.0 as u8 is 0 nan as u8 is 0
广告