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

Rust 101 — พื้นฐาน

คุณรู้จัก TypeScript อยู่แล้ว คุณเข้าใจเรื่อง type, function และวิธีสร้างซอฟต์แวร์จริง ๆ โมดูลนี้ใช้ความรู้เหล่านั้นเป็นสะพานเชื่อม — เราจะเปิดทุกแนวคิดด้วยการเทียบกับสิ่งที่คุณรู้อยู่แล้ว จากนั้นจึงแสดงวิธีแบบ Rust

โมดูลนี้ครอบคลุมองค์ประกอบพื้นฐานของ Rust ที่แมปเข้ากับแพตเทิร์น TypeScript ที่ใช้ในชีวิตประจำวัน:

  • Variableslet, let mut, const, shadowing และ type inference
  • Functions — parameter ที่มี type, return type และไวยากรณ์แบบ expression-oriented
  • Control flowif ในฐานะ expression, match, loop, while, for
  • Structs — ทางเลือกของ Rust แทน class และ interface
  • Enums — algebraic data types และ exhaustive pattern matching
  • CollectionsVec, HashMap, array, tuple, slice
  • Option และ Result — ตัวแทนของ null/undefined และ try/catch
  • Modules และ crates — สิ่งที่เทียบเท่ากับ ESM และ npm ในโลก Rust

เมื่อจบโมดูล คุณจะมีคำศัพท์เพียงพอที่จะอ่านและเขียนโปรแกรม Rust จริง ๆ ได้

ทั้งสองโปรแกรมทักทายผู้ใช้ โครงสร้างคล้ายกัน แต่ Rust เป็นภาษาที่ compile, มี type แบบ static และไม่มี runtime — println! เป็น macro ที่จัดการ format string ตอน compile time

TypeScript
const name = "TypeScript developer";
console.log(`Hello, ${name}! Welcome to Rust.`);
Rust
fn main() {
let name = "TypeScript developer";
println!("Hello, {}! Welcome to Rust.", name);
}

รัน snippet ของ Rust ด้านบนได้โดยตรงในเบราว์เซอร์ของคุณ

fn main() {
let name = "TypeScript developer";
println!("Hello, {}! Welcome to Rust.", name);
}
ใน Rust นั้น println! คืออะไร ?
อะไรคือจุดเริ่มต้น (entry point) ของโปรแกรม binary ทุกตัวใน Rust?