Variables
Variables ใน TypeScript เทียบกับ Rust
หัวข้อที่มีชื่อว่า “Variables ใน TypeScript เทียบกับ Rust”ใน TypeScript นั้น let ประกาศ binding ที่เปลี่ยนค่าได้ (mutable) ส่วน const ประกาศตัวที่เปลี่ยนค่าไม่ได้ (immutable) Rust สลับค่าเริ่มต้นกัน: let เป็น immutable โดยปริยาย และคุณต้องเลือกให้เป็น mutable เองด้วย let mut ส่วน const ของ Rust คล้ายกับของ TypeScript — เป็นค่าคงที่ตอน compile time ที่ต้องระบุ type annotation เสมอ
Type inference และ annotation
หัวข้อที่มีชื่อว่า “Type inference และ annotation”Rust ทำ type inference ได้เหมือนกับ TypeScript คุณสามารถใส่ annotation ระบุชัดเจนได้เมื่อต้องการความชัดเจน หรือเมื่อ compiler ไม่สามารถ infer type ได้ด้วยตัวเอง
// TypeScriptlet score: number = 42;let name = "Alice"; // inferred as string
// Rustlet score: i32 = 42;let name = "Alice"; // inferred as &strShadowing
หัวข้อที่มีชื่อว่า “Shadowing”Rust อนุญาตให้ประกาศตัวแปรชื่อเดิมซ้ำด้วย let ใน scope เดียวกันได้ — เรียกว่า shadowing โดย binding ตัวใหม่จะไปแทนที่ตัวเก่า ซึ่งต่างจากการ mutate: คุณเปลี่ยน type ได้ด้วยซ้ำ ส่วน TypeScript ไม่อนุญาตให้ประกาศชื่อเดิมซ้ำด้วย let ใน scope เดียวกัน
// TypeScript: cannot shadow with let in same scopeconst x = 5;// let x = x + 1; // SyntaxError
// Workaround: use a new name or use let + reassignlet count = 5;count = count + 1;console.log(count); // 6fn main() { let x = 5; // x = 6; // ERROR: cannot assign twice to immutable variable let x = x + 1; // shadowing: a new binding named x println!("{x}"); // 6
let mut y = 10; // explicitly mutable y += 5; println!("{y}"); // 15
const MAX_POINTS: u32 = 100_000; // compile-time constant println!("{MAX_POINTS}");}ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”fn main() { let x = 5; println!("x = {x}"); let x = x + 1; println!("after shadowing, x = {x}"); let mut y = 10; y += 5; println!("mutable y = {y}"); const MAX_POINTS: u32 = 100_000; println!("const MAX_POINTS = {MAX_POINTS}");}Compiling…