Struct, Enum और Trait

Rust Traits

Describe shared behavior once and implement it for any type, like interfaces in other languages.

  • मध्यम
  • 4 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Defining a trait
  • Default methods
  • impl Trait and dyn Trait
trait Describe
  • Describe
    • Dogkeeps the default
    • Robotreplaces describe

Shared behavior for different types

A trait is a set of methods that a type can implement, similar to an interface in other languages. Code written against the trait works with every type that implements it.

Describe requires name and gives describe a default body. Dog keeps the default, while Robot replaces it. introduce accepts any type that implements Describe, and Box<dyn Describe> lets one vector hold values of different types.

मुख्य बातें

  1. A trait lists methods a type must have.
  2. A default method can be kept or replaced.
  3. Box<dyn Trait> stores different types together.

चलने योग्य Rust उदाहरण

Rust
कोड चलाएँ →
main.rs
trait Describe {
    fn name(&self) -> String;

    fn describe(&self) -> String {
        format!("This is {}.", self.name())
    }
}

struct Dog;
struct Robot {
    model: u32,
}

impl Describe for Dog {
    fn name(&self) -> String {
        String::from("a dog")
    }
}

impl Describe for Robot {
    fn name(&self) -> String {
        format!("robot model {}", self.model)
    }

    fn describe(&self) -> String {
        format!("Beep. I am {}.", self.name())
    }
}

fn introduce(item: &impl Describe) {
    println!("{}", item.describe());
}

fn main() {
    introduce(&Dog);
    introduce(&Robot { model: 7 });

    let items: Vec<Box<dyn Describe>> = vec![Box::new(Dog), Box::new(Robot { model: 8 })];
    println!("{} items", items.len());
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
This is a dog.
Beep. I am robot model 7.
2 items

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Generics →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज