Type Conversions
Rust เป็นภาษาที่มี Strong Static Typing คือ Type ต้องเป๊ะมาก จะมาบวกเลข i32 กับ i64 ดื้อๆ ไม่ได้นะจ๊ะ Compiler ตบหัวทิ่มแน่นอน
ลองนึกภาพว่าการแปลง Type เป็นเหมือน “การแปลงสกุลเงิน” - ต้องระวังเรื่องอัตราแลกเปลี่ยนและการปัดเศษ!
1. as Keyword - Primitive Casting
Section titled “1. as Keyword - Primitive Casting”1.1 Numeric Casting
Section titled “1.1 Numeric Casting”fn main() { // ============================================ // as = cast ระหว่าง primitive types // ============================================
let x: i32 = 42; let y: i64 = x as i64; // Safe - widening println!("i32 -> i64: {} -> {}", x, y);
// ============================================ // Float to int = ตัดทศนิยมทิ้ง (truncate) // ============================================ let a: f64 = 3.14; let b: i32 = a as i32; // 3.14 -> 3 println!("f64 -> i32: {} -> {} (truncated)", a, b);
let c: f64 = -3.99; let d: i32 = c as i32; // -3.99 -> -3 (truncate toward zero) println!("f64 -> i32: {} -> {}", c, d);
// ============================================ // Int to float // ============================================ let e: i32 = 42; let f: f64 = e as f64; println!("i32 -> f64: {} -> {}", e, f);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google