let a: i32 = 100;
let b: u8 = a as u8; // 將 i32 強制轉為 u8
✅ as 的作用:
let big: u16 = 300;
let small: u8 = big as u8; // ❗ small 會變成 44(因為 300 超出 u8 範圍)
⚠️ 注意:
as 不會檢查資料是否溢位,因為它是「不安全但允許的轉換(lossy conversion)」,你要自己負責確認值的安全性。
fn main() {
let x: i32 = 42;
let y: f64 = x as f64; // i32 轉為 f64
let z: u8 = x as u8; // i32 轉為 u8
println!("{}, {}, {}", x, y, z);
}
以上為範例補充。
fn main() {
let additiion = 5 + 4;
let subtraction = 10 - 6;
let multiplication = 3 * 4;
println!(
"Addition:{}, Subtraction:{}, Multiplication:{}",
additiion, subtraction, multiplication
);
let floor_division = 5 / 3;
println!("{}", floor_division);
//整數除法(floor division):5 / 3 結果為 1(小數會被截斷,只保留整數部分)。
let deciaml_division = 5.0 / 3.0;
println!("{}", deciaml_division);
//浮點數除法:5.0 / 3.0 結果為 1.6666...(精確保留小數)。
let remainder = 9 % 2;
println!("{}", remainder);
//取餘數:9 除以 2 的餘數是 1(也稱為 modulo 運算)。
}
fn main() {
let mut year = 2025;
year += 1;
println!("The new year is {}", year); // 2026
year -= 5;
println!("The new year is {}", year); // 2021
year *= 2;
println!("The new year is {}", year); // 4042
year /= 4;
println!("The new year is {}", year); // 1010
}