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

Trait के Basics

एक trait एक promise है जो कहता है "मुझे उपयोग करने वाला कोई भी type जानता है कि ये particular चीज़ें कैसे करनी हैं।"
Syntax
rust
trait Name {
    fn method(&self) -> ReturnType;
}

impl Name for Type {
    fn method(&self) -> ReturnType {
        // body
    }
}

Defining a Trait

trait keyword method signatures का एक set define करता है जो किसी भी implementing type को प्रदान करना चाहिए, shared behavior describe करते हुए बिना यह तय किए कि यह कैसे stored है।

उदाहरण: Defining a Trait

markup
// Define a trait `Greet` describing shared behavior
trait Greet {
    // Define the function `greet` taking `&self` and returning a `String;`
    fn greet(&self) -> String;
}

// Define a struct `Person` to group related fields together
struct Person {
    name: String,
}

// Implement the `Greet` trait for `Person`
impl Greet for Person {
    // Define the function `greet` taking `&self` and returning a String
    fn greet(&self) -> String {
        format!("Hello, my name is {}", self.name)
    }
}

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

Implementing a Trait for Multiple Types

उसी trait को कई unrelated types के लिए implement किया जा सकता है, हर एक required behavior का अपना version प्रदान करते हुए।

उदाहरण: Implementing a Trait for Multiple Types

markup
// Define a trait `Greet` describing shared behavior
trait Greet {
    // Define the function `greet` taking `&self` and returning a `String;`
    fn greet(&self) -> String;
}

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

// Implement the `Greet` trait for `Robot`
impl Greet for Robot {
    // Define the function `greet` taking `&self` and returning a String
    fn greet(&self) -> String {
        String::from("BEEP BOOP HELLO")
    }
}

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

A Type Implementing Multiple Traits

एक single type ज़रूरत के अनुसार कितने भी अलग-अलग traits implement कर सकता है, हर एक उस type में behavior का एक अलग टुकड़ा जोड़ते हुए।

उदाहरण: A Type Implementing Multiple Traits

markup
// Define a trait `Greet` describing shared behavior
trait Greet {
    // Define the function `greet` taking `&self` and returning a `String;`
    fn greet(&self) -> String;
}

// Define a trait `Farewell` describing shared behavior
trait Farewell {
    // Define the function `farewell` taking `&self` and returning a `String;`
    fn farewell(&self) -> String;
}

// Define a struct `Person` to group related fields together
struct Person {
    name: String,
}

// Implement the `Greet` trait for `Person`
impl Greet for Person {
    // Define the function `greet` taking `&self` and returning a String
    fn greet(&self) -> String {
        format!("Hi, {}", self.name)
    }
}

// Implement the `Farewell` trait for `Person`
impl Farewell for Person {
    // Define the function `farewell` taking `&self` and returning a String
    fn farewell(&self) -> String {
        format!("Bye, {}", self.name)
    }
}

// Entry point: execution of the program starts here
fn main() {
    let p = Person { name: String::from("Lee") };
    println!("{}", p.greet());
    println!("{}", p.farewell());
}

Calling Trait Methods Through the Trait

एक बार कोई trait किसी type के लिए implement हो जाए, इसके methods ordinary dot syntax उपयोग करके call किए जाते हैं, बिल्कुल किसी और method की तरह, जब तक trait scope में हो।

उदाहरण: Calling Trait Methods Through the Trait

markup
// Define a trait `Area` describing shared behavior
trait Area {
    // Define the function `area` taking `&self` and returning a `f64;`
    fn area(&self) -> f64;
}

// Define a struct `Square` to group related fields together
struct Square {
    side: f64,
}

// Implement the `Area` trait for `Square`
impl Area for Square {
    // Define the function `area` taking `&self` and returning a floating-point number
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `sq`, set to `Square { side: 4.0 }`
    let sq = Square { side: 4.0 };
    // Print "Area: {}" to the console, substituting in `sq.area()` (with a trailing newline)
    println!("Area: {}", sq.area());
}
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. किसी type पर इसके methods call करने से पहले use से किसी trait को scope में लाना भूल जाना, भले ही impl कहीं और मौजूद हो।
  2. किसी trait definition को struct के साथ confuse करना -- traits shared behavior describe करते हैं, वे खुद data नहीं रखते।
  3. किसी trait के method को उस signature से अलग signature से implement करना जो trait declare करता है, जो compile होने में fail होता है।
चैप्टर सारांश
  • एक trait method signatures का एक set define करता है जो implementing types प्रदान करने के लिए सहमत होते हैं।
  • impl TraitName for TypeName { ... } किसी specific type के लिए असली behavior प्रदान करता है।
  • एक single type कई अलग-अलग traits implement कर सकता है।
  • Traits अन्यथा unrelated types में shared behavior enable करते हैं, दूसरी languages में interfaces के समान।
🔒

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.