Traits & Generics
ถ้าคุณเคยเขียน Java แล้วรู้จัก Interface หรือเขียน C++ แล้วรู้จัก Template ใน Rust เราเรียกสองสิ่งนี้ว่า Trait และ Generics ครับ
ลองนึกภาพว่า Trait เป็นเหมือน “สัญญา” ที่บอกว่า type นี้ทำอะไรได้บ้าง และ Generics เป็นเหมือน “template” ที่ใช้ได้กับหลาย types!
1. Traits
Section titled “1. Traits”1.1 Basic Trait
Section titled “1.1 Basic Trait”// ============================================// trait = กำหนด behaviors ที่ types ต้อง implement// ============================================trait Summary { fn summarize(&self) -> String;}
struct Article { headline: String, content: String,}
struct Tweet { username: String, content: String,}
// ============================================// impl Trait for Type// ============================================impl Summary for Article { fn summarize(&self) -> String { format!("{}...", self.headline) }}
impl Summary for Tweet { fn summarize(&self) -> String { format!("@{}: {}", self.username, self.content) }}
fn main() { let article = Article { headline: String::from("Rust News"), content: String::from("..."), }; let tweet = Tweet { username: String::from("rustlang"), content: String::from("Rust 1.75!"), };
println!("{}", article.summarize()); println!("{}", tweet.summarize());}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google