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

Rust ขั้นสูง

คุณได้เรียนรู้ระบบ ownership, borrowing, และ type พื้นฐานของ Rust แล้ว ถึงเวลาปลดล็อกเครื่องมือที่ทำให้ Rust ทั้งมีพลังในการแสดงออกและมีต้นทุนเป็นศูนย์: ระบบ type ที่มีประสิทธิภาพพอที่จะแทนที่ framework ทั้งหมดในขณะ runtime ด้วยการรับประกันในขณะ compile time

บทเรียนนี้นำแต่ละแนวคิดไปเชื่อมกับสิ่งที่คุณรู้อยู่แล้วจาก TypeScript เพื่อให้คุณสร้าง mental model ได้อย่างรวดเร็ว

บทเรียนแนวคิด Rustคู่เทียบใน TypeScript
Generics & Trait Boundsfn foo<T: Display>(), where clausesGeneric functions พร้อม constraints <T extends ...>
Trait Objectsdyn Trait, Box<dyn Trait>Interfaces, polymorphism, runtime dispatch
Closures & IteratorsFn/FnMut/FnOnce, .map()/.filter()/.collect()Arrow functions, Array.prototype.map/filter/reduce
Error Handling (ลึก)? operator, thiserror, anyhowtry/catch, typed error classes
Macrosmacro_rules!, derive macrosไม่มีคู่เทียบตรงๆ — แต่ใกล้เคียง TypeScript decorators
Smart PointersBox<T>, Rc<T>, RefCell<T>JavaScript references ที่ถูกจัดการโดย GC

TypeScript มี generic, interface และ union error type อยู่แล้ว ส่วน Rust ดันทั้งสามเรื่องนี้ไปอีกขั้น:

  • Generics ถูก monomorphise — compiler สร้างสำเนาเฉพาะสำหรับแต่ละ concrete type ไม่มี overhead จาก virtual dispatch
  • Trait objects (dyn Trait) ให้ runtime polymorphism ที่คุณคุ้นเคยจาก TypeScript interfaces แต่คุณต้องเลือกใช้อย่างชัดเจน
  • Closures จับค่าโดย reference หรือโดย move และ Fn* trait hierarchy บอก compiler ว่า closure ทำอะไรได้บ้าง
  • Error handling ด้วย ? และ thiserror ใช้งานง่ายพอๆ กับ async/await — และ type บังคับให้คุณจัดการทุก failure case
  • Macros มีความ hygienic และทำงานบน AST — มีพลังมากกว่าและปลอดภัยกว่า TypeScript string-template code generation
  • Smart pointers ให้การควบคุม heap allocation และ shared ownership อย่างละเอียดโดยไม่ต้องมี GC

เรียนบทเรียนตามลำดับ แต่ละบทสร้างต่อจากบทก่อนหน้า

Rust generics ถูก monomorphise หมายความว่าอะไร?
ฟีเจอร์ใดของ Rust ที่ใกล้เคียงกับ TypeScript interface-based polymorphism ขณะ runtime มากที่สุด?
ข้อได้เปรียบหลักของ `?` operator ของ Rust เมื่อเทียบกับ TypeScript's try/catch คืออะไร?