As Casts Follow Lossy Rules

Demonstrate as conversions honestly: wide integers truncate, signed bit patterns reinterpret, char maps to its code point, floats saturate.

RustData Integrity

Code

rustsnippet
26 lines
fn main() {
    // as 数值转换是有损重解释:超范围直接截断,不检查、不 panic
    let big: i64 = 300;
    println!("300 as u8 = {}", big as u8); // 300 & 0xFF = 44

    // 有符号到无符号:按位模式重解释,-1 变成最大值
    let negative: i8 = -1;
    println!("-1 as u8 = {}", negative as u8);

    // 无符号加宽到 i32:零扩展,安全
    let byte: u8 = 200;
    println!("200 as i32 = {}", byte as i32);

    // 反方向截断:1000 的低 8 位重解释为 i8
    println!("1000 as i8 = {}", 1000_i32 as i8);

    // char <-> u32:as 在 Unicode 标量值上往返
    let letter = '中';
    let code = letter as u32;
    println!("{letter} = U+{code:04X}");
    println!("back: {}", char::from_u32(code).unwrap());

    // 浮点 as 整型:向零截断;超出范围时饱和到边界(Rust 1.45+)
    println!("2.9 as i32 = {}", 2.9_f64 as i32);
    println!("1e30 as i32 = {}", 1e30_f64 as i32);
}

Inside the snippet

As Casts Follow Lossy Rules keeps everything in the function main.

Using it

The run emits 7 labeled sections — 300 as u8 =, -1 as u8 =, 200 as i32 =, 1000 as i8 =, back:, 2.9 as i32 =, 1e30 as i32 = — one per step.

Key statements

let code = letter as u32;
let negative: i8 = -1;
let big: i64 = 300;

Interactive Tools for This Topic

FAQ

What does As Casts Follow Lossy Rules print when run?
No setup needed: run the file and look for labeled lines like `300 as u8 =`, `-1 as u8 =`, `200 as i32 =` in the output.