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

Generic Structs क्या हैं

एक generic struct एक container है जिसे आप एक बार design करते हैं, लेकिन यह जो भी value आप बाद में डालना चाहें रख सकता है।
Syntax
rust
struct Name<T> {
    field: T,
}

impl<T> Name<T> {
    fn method(&self) -> &T {
        &self.field
    }
}

Defining a Generic Struct

एक struct एक या ज़्यादा type parameters पर generic हो सकता है, एक जैसी struct definition को अलग instances में अलग concrete types रखने देते हुए।

उदाहरण: Defining a Generic Struct

markup
// Define a struct `Wrapper` to group related fields together
struct Wrapper<T> {
    value: T,
}

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

Generic Struct with Multiple Type Parameters

एक struct एक से ज़्यादा generic type parameter उपयोग कर सकता है, इसकी fields को independent, संभवतः अलग concrete types रखने देते हुए।

उदाहरण: Generic Struct with Multiple Type Parameters

markup
// Define a struct `Pair` to group related fields together
struct Pair<A, B> {
    first: A,
    second: B,
}

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

Methods on a Generic Struct

किसी generic struct के लिए एक impl block type parameter दोहराता है, methods को struct की generic field के साथ काम करने देते हुए चाहे यह कौन सा concrete type रखता हो।

उदाहरण: Methods on a Generic Struct

markup
// Define a struct `Wrapper` to group related fields together
struct Wrapper<T> {
    value: T,
}

// Implement methods on `Wrapper`
impl<T> Wrapper<T> {
    // Define the function `get` taking `&self` and returning a `&T`
    fn get(&self) -> &T {
        &self.value
    }
}

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

Adding Trait Bounds on Methods

Individual methods struct खुद जो चाहता है उससे आगे trait bounds जोड़ सकते हैं, उस specific method को ज़रूरी capability वाले types तक restrict करते हुए।

उदाहरण: Adding Trait Bounds on Methods

markup
// Define a struct `Pair` to group related fields together
struct Pair<T> {
    a: T,
    b: T,
}

// Implement methods on `Pair`
impl<T: PartialOrd + std::fmt::Display> Pair<T> {
    // Define the function `larger` taking `&self` and returning a `&T`
    fn larger(&self) -> &T {
        // Check whether `self.a > self.b { &self.a } else { &self.b }`
        if self.a > self.b { &self.a } else { &self.b }
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `pair`, set to `Pair { a: 10, b: 20 }`
    let pair = Pair { a: 10, b: 20 };
    // Print "Larger: {}" to the console, substituting in `pair.larger()` (with a trailing newline)
    println!("Larger: {}", pair.larger());
}
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. T को किसी field के type के रूप में उपयोग करने से पहले struct पर खुद <T> declare करना भूल जाना।
  2. यह मान लेना कि एक type parameter <T> वाला generic struct दो fields में टाइप T के दो अलग types रख सकता है -- दोनों fields को उसी concrete type से match करना चाहिए।
  3. किसी method के लिए trait bound न जोड़ना जब impl block के अंदर इसे एक operation perform करना है जो सिर्फ कुछ types support करते हैं।
चैप्टर सारांश
  • एक generic struct अपना type parameter angle brackets में declare करता है, जैसे struct Wrapper<T> { value: T }।
  • उसी generic parameter T से typed सभी fields को एक instance के अंदर उसी concrete type को रखना चाहिए।
  • Methods struct की खुद की declaration से आगे extra trait bounds जोड़ सकते हैं जब उन्हें specific capabilities चाहिए।
  • Generic structs आपको store करने के लिए चाहे हर concrete kind of data के लिए near-duplicate types लिखने से बचाते हैं।
🔒

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.