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

Structs

TypeScript ใช้ class เพื่อรวมข้อมูลและพฤติกรรมเข้าด้วยกัน และใช้ interface หรือ object literal สำหรับรูปทรงของข้อมูลล้วน ๆ ส่วน Rust แยกข้อมูลออกจากพฤติกรรม: struct เก็บข้อมูล ส่วน impl block ผูก method เข้ากับ struct นั้น ไม่มี inheritance — composition คือวิถีของ Rust

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 block แยกต่างหาก ตัวที่แค่อ่านข้อมูลรับ &self (immutable reference) ส่วนตัวที่ mutate รับ &mut self และ function ใน impl ที่ไม่มี parameter self ถือเป็น associated function — เรียกด้วยไวยากรณ์ :: มักใช้เป็น constructor

TypeScript
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()); // 5
Rust
struct 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());
}
ใน Rust คุณนิยาม method ของ struct ไว้ที่ไหน?
`&self` ใน signature ของ method ใน Rust หมายความว่าอะไร?
คุณเรียก associated function (เช่น constructor) บน struct ชื่อ `Point` ของ Rust อย่างไร?