iT邦幫忙

1

二、三天學一點點 Rust:來!as型別轉換、基本數學運算(9)

  • 分享至 

  • xImage
  •  

🧠 Rust中的 as 型別轉換

在Rust裡,as 是一個關鍵字(keyword),用來做「顯式型別轉換(explicit type casting)」。

📌 基本語法:

let a: i32 = 100;
let b: u8 = a as u8;  // 將 i32 強制轉為 u8

✅ as 的作用:

  • 將一個數值從一種型別「強制轉換」為另一種型別
  • 適用於:整數轉換(如 i32 → u8)、數字 → 浮點數(i32 → f64)、指標等進階用途
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);
}

以上為範例補充。

🧠基本數學運算(Math operations)

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
}

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言