Rust:Rust में Traits: साझा व्यवहार और बहुरूपता (Polymorphism)
Rust•Traits

Rust में Traits: साझा व्यवहार और बहुरूपता (Polymorphism)

Rust पारंपरिक इनहेरिटेंस के बजाय traits का उपयोग करके विभिन्न टाइप्स के बीच साझा क्षमताओं का अनुबंध तय करता है।

सिंटैक्स

trait Describable { fn describe(&self) -> String; }

पैरामीटर और मान

इस संरचना के मुख्य घटक और मान्य मान:

पैरामीटरप्रकारविवरण
traitKeywordसाझा व्यवहार अनुबंध परिभाषित करता है।

चलाने के लिए तैयार कोड उदाहरण

Compilra में निष्पादन योग्य

स्थानीय रूप से Rust इंस्टॉल किए बिना इस पूर्ण, कार्यशील उदाहरण को सीधे चलाएं:

trait HealthChecker {
    fn check_health(&self) -> String;
}

struct DatabaseNode {
    name: String,
    active_conns: u32,
}

impl HealthChecker for DatabaseNode {
    fn check_health(&self) -> String {
        format!("{}: OK ({} active connections)", self.name, self.active_conns)
    }
}

// Function accepting generic type bounded by trait
fn run_diagnostic<T: HealthChecker>(item: &T) {
    println!("[DIAGNOSTIC] {}", item.check_health());
}

fn main() {
    let db = DatabaseNode {
        name: String::from("PostgresCluster"),
        active_conns: 42,
    };
    run_diagnostic(&db);
}
अपेक्षित आउटपुट:
[DIAGNOSTIC] PostgresCluster: OK (42 active connections)

यह कैसे काम करता है: चरण-दर-चरण

  • पंक्तियाँ 1-3: HealthChecker trait परिभाषित करता है।
  • पंक्तियाँ 10-14: DatabaseNode के लिए trait लागू करता है।
  • पंक्तियाँ 17-19: जेनेरिक फ़ंक्शन स्टैटिक मोनोमॉर्फ़ाइज़ेशन के लिए <T: HealthChecker> trait bound उपयोग करता है।

मुख्य अवधारणाएं

  • Rust में traits इंटरफ़ेस और एब्स्ट्रैक्ट बेस क्लास का स्थान लेते हैं।
  • trait bounds कंपाइल समय पर ज़ीरो-कॉस्ट मोनोमॉर्फ़ाइज़्ड कोड तैयार करते हैं।
  • डायनामिक डिस्पैच trait ऑब्जेक्ट्स (&dyn Trait) से प्राप्त होता है।

सामान्य त्रुटि: किसी बेस struct से फ़ील्ड्स इनहेरिट करने का प्रयास करना

Rust में struct इनहेरिटेंस नहीं होता। इसके बजाय कंपोज़िशन (एक struct के भीतर दूसरा struct रखना) और traits उपयोग करें।

❌ गलत
struct Child : Parent { ... } // Syntax Error!
✅ सही
struct Child { parent_data: Parent, extra: u32 }

संबंधित Rust ट्यूटोरियल और कंपाइलर

Compilra पर Rust चलाएं और परीक्षण करें

Compilra के क्लाउड कंपाइलर में पूर्व-प्रदत्त स्टैंडर्ड इनपुट (stdin) के साथ इस कोड स्निपेट को चलाएं।

Rust ऑनलाइन कंपाइलर