Structs
Structs ใน TypeScript เทียบกับ Rust
หัวข้อที่มีชื่อว่า “Structs ใน TypeScript เทียบกับ Rust”TypeScript ใช้ class เพื่อรวมข้อมูลและพฤติกรรมเข้าด้วยกัน และใช้ interface หรือ object literal สำหรับรูปทรงของข้อมูลล้วน ๆ ส่วน Rust แยกข้อมูลออกจากพฤติกรรม: struct เก็บข้อมูล ส่วน impl block ผูก method เข้ากับ struct นั้น ไม่มี inheritance — composition คือวิถีของ Rust
การนิยาม struct
หัวข้อที่มีชื่อว่า “การนิยาม struct”struct เปรียบเหมือน interface ของ TypeScript ที่เก็บข้อมูลได้จริง:
// TypeScript interface (shape only)interface Point { x: number; y: number; }
// Rust struct (data + can have methods)struct Point { x: f64, y: f64 }เพิ่ม method ด้วย impl
หัวข้อที่มีชื่อว่า “เพิ่ม method ด้วย impl”method อยู่ใน impl block แยกต่างหาก ตัวที่แค่อ่านข้อมูลรับ &self (immutable reference) ส่วนตัวที่ mutate รับ &mut self และ function ใน impl ที่ไม่มี parameter self ถือเป็น associated function — เรียกด้วยไวยากรณ์ :: มักใช้เป็น constructor
class Point { constructor(public x: number, public y: number) {}
static new(x: number, y: number) { return new Point(x, y); }
distanceFromOrigin(): number { return Math.sqrt(this.x ** 2 + this.y ** 2); }}
const p = Point.new(3, 4);console.log(p.distanceFromOrigin()); // 5struct Point { x: f64, y: f64,}
impl Point { // associated function (constructor) — called with Point::new(...) fn new(x: f64, y: f64) -> Self { Point { x, y } }
// method — called with p.distance_from_origin() fn distance_from_origin(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() }}
fn main() { let p = Point::new(3.0, 4.0); println!("{}", p.distance_from_origin()); // 5}ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”struct Point { x: f64, y: f64,}
impl Point { fn new(x: f64, y: f64) -> Self { Point { x, y } }
fn distance_from_origin(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() }}
fn main() { let p = Point::new(3.0, 4.0); println!("distance = {}", p.distance_from_origin());}Compiling…