let result = 1; // 默认类型为i32 let u20:u32 = 20; leti32:i32 = -15; let s:isize = 10; let count:usize = 30; println!("result value is {}",result); println!("u20 is {} i32 is {}",u20,i32); println!("mark is {} and count is {}",s,count);
Console
1 2 3
result value is 1 u20 is 20 i32 is -15 mark is 10 and count is 30
整型溢出
当分配给整型变量的值超出该整型在 Rust 中定义值的范围时,就会发生整型溢出
案例
1 2 3 4 5 6 7 8 9 10
let u1:u8 = 255; // u8数据范围为0~255 let u2:u8 = 256; //溢出值为 1 let u3:u8 = 257; //溢出值为 2 let u4:u8 = 258; //溢出值为 3
println!("1 is {} ",u1); println!("2 is {}",u2); println!("3 is {}",u3); println!("4 is {}",u4);
error: literal out of range for `u8` --> src/main.rs:24:16 | 24 | let u2:u8 = 256; //溢出值为 1 | ^^^ | = note: `#[deny(overflowing_literals)]` on by default = note: the literal `256` does not fit into the type `u8` whose range is `0..=255`
error: literal out of range for `u8` --> src/main.rs:25:16 | 25 | let u3:u8 = 257; //溢出值为 2 | ^^^ | = note: the literal `257` does not fit into the type `u8` whose range is `0..=255`
error: literal out of range for `u8` --> src/main.rs:26:16 | 26 | let u4:u8 = 258; //溢出值为 3 | ^^^ | = note: the literal `258` does not fit into the type `u8` whose range is `0..=255`
error: could not compile `learning-02` due to 3 previous errors