← Back to Rust Course | Chapter 11: Generics & Traits | Lesson 5 of 7

Default Trait Implementations क्या हैं

एक default implementation एक ready-made behavior है जो एक trait free में प्रदान करता है, जिसे types जैसा है वैसा उपयोग कर सकते हैं या अपने खुद से replace कर सकते हैं।
Syntax
rust
trait Name {
    fn required(&self);
    fn provided(&self) {
        // default body
    }
}

impl Name for Type {
    fn required(&self) {}
}

Defining a Default Method

एक trait method trait definition में सीधे एक body include कर सकता है, और trait implement करने वाला कोई भी type अपने आप वह behavior पाता है जब तक यह इसे override न करे।

उदाहरण: Defining a Default Method

markup
// Define a trait `Summary` describing shared behavior
trait Summary {
    // Define the function `summarize` taking `&self` and returning a String
    fn summarize(&self) -> String {
        String::from("(no summary available)")
    }
}

// Define a struct `Article` to group related fields together
struct Article;

// Implement the `Summary` trait for `Article`
impl Summary for Article {}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `a`, set to `Article`
    let a = Article;
    // Print "{}" to the console, substituting in `a.summarize()` (with a trailing newline)
    println!("{}", a.summarize());
}

Overriding a Default Method

Trait implement करने वाला एक type अब भी एक default वाली method का अपना version प्रदान कर सकता है, उस type के लिए default behavior को पूरी तरह replace करते हुए।

उदाहरण: Overriding a Default Method

markup
// Define a trait `Summary` describing shared behavior
trait Summary {
    // Define the function `summarize` taking `&self` and returning a String
    fn summarize(&self) -> String {
        String::from("(no summary available)")
    }
}

// Define a struct `Post` to group related fields together
struct Post {
    title: String,
}

// Implement the `Summary` trait for `Post`
impl Summary for Post {
    // Define the function `summarize` taking `&self` and returning a String
    fn summarize(&self) -> String {
        format!("Post: {}", self.title)
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `post`, set to `Post { title: String::from("Rust Traits") }`
    let post = Post { title: String::from("Rust Traits") };
    // Print "{}" to the console, substituting in `post.summarize()` (with a trailing newline)
    println!("{}", post.summarize());
}

Default Methods Calling Required Methods

एक default method उसी trait की किसी दूसरी method को call कर सकता है जिसका कोई default नहीं, हर implementing type पर वह required टुकड़ा प्रदान करने के लिए भरोसा करते हुए जबकि इसके आस-पास shared logic reuse करते हुए।

उदाहरण: Default Methods Calling Required Methods

markup
// Define a trait `Greeting` describing shared behavior
trait Greeting {
    // Define the function `name` taking `&self` and returning a `String;`
    fn name(&self) -> String;
    // Define the function `greet` taking `&self` and returning a String
    fn greet(&self) -> String {
        format!("Hello, {}!", self.name())
    }
}

// Define a struct `User` to group related fields together
struct User {
    username: String,
}

// Implement the `Greeting` trait for `User`
impl Greeting for User {
    // Define the function `name` taking `&self` and returning a String
    fn name(&self) -> String {
        self.username.clone()
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `u`, set to `User { username: String::from("kai") }`
    let u = User { username: String::from("kai") };
    // Print "{}" to the console, substituting in `u.greet()` (with a trailing newline)
    println!("{}", u.greet());
}

Mixing Default and Overridden Methods

एक trait में कई methods हो सकते हैं, कुछ defaults वाले और कुछ किसी दिए type से overridden, हर implementer को सिर्फ उतना ही customize करते हुए convenient shared logic reuse करने देते हुए।

उदाहरण: Mixing Default and Overridden Methods

markup
// Define a trait `Vehicle` describing shared behavior
trait Vehicle {
    // Define the function `wheels` taking `&self` and returning an unsigned integer
    fn wheels(&self) -> u32 {
        4
    }
    // Define the function `describe` taking `&self` and returning a String
    fn describe(&self) -> String {
        format!("A vehicle with {} wheels", self.wheels())
    }
}

// Define a struct `Motorcycle` to group related fields together
struct Motorcycle;

// Implement the `Vehicle` trait for `Motorcycle`
impl Vehicle for Motorcycle {
    // Define the function `wheels` taking `&self` and returning an unsigned integer
    fn wheels(&self) -> u32 {
        2
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `m`, set to `Motorcycle`
    let m = Motorcycle;
    // Print "{}" to the console, substituting in `m.describe()` (with a trailing newline)
    println!("{}", m.describe());
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि हर trait method को हर type द्वारा फिर से implement किया जाना चाहिए -- default implementations आपको यह skip करने देते हैं जब default fit हो।
  2. यह भूल जाना कि एक default method अब भी उसी trait के दूसरे required (non-default) methods call कर सकता है, हर implementer पर उन्हें प्रदान करने के लिए भरोसा करते हुए।
  3. एक default method को गलती से एक अलग signature के साथ फिर से define करके अनजाने में override करना।
चैप्टर सारांश
  • एक trait method एक default body प्रदान कर सकता है, जिसे implementing types अपने आप inherit करते हैं जब तक इसे override न करें।
  • Types अब भी एक default implementation को अपने custom version से override करना चुन सकते हैं।
  • Default methods उसी trait के दूसरे methods call कर सकते हैं, यहां तक कि बिना default वाले भी, हर type पर उन्हें supply करने के लिए भरोसा करते हुए।
  • Default implementations उसी trait implement करने वाले कई types में repetitive boilerplate घटाते हैं।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.