ข้ามไปยังเนื้อหา

Variables

ใน TypeScript นั้น let ประกาศ binding ที่เปลี่ยนค่าได้ (mutable) ส่วน const ประกาศตัวที่เปลี่ยนค่าไม่ได้ (immutable) Rust สลับค่าเริ่มต้นกัน: let เป็น immutable โดยปริยาย และคุณต้องเลือกให้เป็น mutable เองด้วย let mut ส่วน const ของ Rust คล้ายกับของ TypeScript — เป็นค่าคงที่ตอน compile time ที่ต้องระบุ type annotation เสมอ

Rust ทำ type inference ได้เหมือนกับ TypeScript คุณสามารถใส่ annotation ระบุชัดเจนได้เมื่อต้องการความชัดเจน หรือเมื่อ compiler ไม่สามารถ infer type ได้ด้วยตัวเอง

// TypeScript
let score: number = 42;
let name = "Alice"; // inferred as string
// Rust
let score: i32 = 42;
let name = "Alice"; // inferred as &str

Rust อนุญาตให้ประกาศตัวแปรชื่อเดิมซ้ำด้วย let ใน scope เดียวกันได้ — เรียกว่า shadowing โดย binding ตัวใหม่จะไปแทนที่ตัวเก่า ซึ่งต่างจากการ mutate: คุณเปลี่ยน type ได้ด้วยซ้ำ ส่วน TypeScript ไม่อนุญาตให้ประกาศชื่อเดิมซ้ำด้วย let ใน scope เดียวกัน

TypeScript
// TypeScript: cannot shadow with let in same scope
const x = 5;
// let x = x + 1; // SyntaxError
// Workaround: use a new name or use let + reassign
let count = 5;
count = count + 1;
console.log(count); // 6
Rust
fn 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}");
}
`let x = 5;` สร้างอะไรขึ้นมาใน Rust?
คุณใช้ keyword ไหนเพื่ออนุญาตให้ reassign ตัวแปรใน Rust ได้?
shadowing ใน Rust คืออะไร?