← Back to Rust Course | Chapter 7: Structs | Lesson 4 of 7

Associated Functions क्या हैं

एक associated function किसी struct के toolbox से belong करता है लेकिन चलने के लिए एक असली struct instance की ज़रूरत नहीं -- एक factory की तरह जो नए बनाता है।
Syntax
rust
impl Name {
    fn new(param: Type) -> Self {
        Self { field: param }
    }
}

let value = Name::new(arg);

Defining an Associated Function

एक associated function एक impl block के अंदर बिल्कुल एक method की तरह रहता है, लेकिन self नहीं लेता, मतलब यह किसी मौजूदा instance पर call नहीं होता।

उदाहरण: Defining an Associated Function

markup
// Define a struct `Point` to group related fields together
struct Point {
    x: i32,
    y: i32,
}

// Implement methods on `Point`
impl Point {
    // Define the function `origin` with no parameters and returning a `Point`
    fn origin() -> Point {
        Point { x: 0, y: 0 }
    }
}

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

The new Convention

एक strong community convention से, किसी struct का primary constructor-जैसा associated function new नाम का होता है, भले ही Rust में कोई special built-in new keyword नहीं है।

उदाहरण: The new Convention

markup
// Define a struct `Rectangle` to group related fields together
struct Rectangle {
    width: f64,
    height: f64,
}

// Implement methods on `Rectangle`
impl Rectangle {
    // Define the function `new` taking `width`, `height` and returning a `Rectangle`
    fn new(width: f64, height: f64) -> Rectangle {
        Rectangle { width, height }
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `rect`, set to `Rectangle::new(4.0, 5.0)`
    let rect = Rectangle::new(4.0, 5.0);
    // Print "{} x {}" to the console, substituting in `rect.width, rect.height` (with a trailing newline)
    println!("{} x {}", rect.width, rect.height);
}

Calling with Type::function() Syntax

चूंकि associated functions में कोई self नहीं, इन्हें type name और double colon उपयोग करके call किया जाता है, Type::function_name(), किसी instance पर dot syntax के बजाय।

उदाहरण: Calling with Type::function() Syntax

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

// Implement methods on `Square`
impl Square {
    // Define the function `unit` with no parameters and returning a `Square`
    fn unit() -> Square {
        Square { side: 1.0 }
    }
}

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

Multiple Associated Constructors

एक struct कई अलग-अलग associated functions define कर सकता है जो हर एक अलग तरीके से एक instance construct करता है, callers को convenient, clearly-named alternatives देते हुए।

उदाहरण: Multiple Associated Constructors

markup
// Define a struct `Color` to group related fields together
struct Color {
    r: u8,
    g: u8,
    b: u8,
}

// Implement methods on `Color`
impl Color {
    // Define the function `black` with no parameters and returning a `Color`
    fn black() -> Color {
        Color { r: 0, g: 0, b: 0 }
    }
    // Define the function `white` with no parameters and returning a `Color`
    fn white() -> Color {
        Color { r: 255, g: 255, b: 255 }
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `bg`, set to `Color::white()`
    let bg = Color::white();
    // Print "Background: ({}, {}, {})" to the console, substituting in `bg.r, bg.g, bg.b` (with a trailing newline)
    println!("Background: ({}, {}, {})", bg.r, bg.g, bg.b);
}
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. एक associated function को dot syntax जैसे instance.new() से call करने की कोशिश करना बजाय सही Type::new() syntax के।
  2. यह भूल जाना कि associated functions बिल्कुल self नहीं लेते, regular methods के विपरीत।
  3. किसी struct के simple constructor function को new नाम देने के community convention को follow न करना।
चैप्टर सारांश
  • एक associated function एक impl block के अंदर defined होता है लेकिन एक parameter के रूप में self नहीं लेता।
  • Associated functions Type::function_name() syntax उपयोग करके call किए जाते हैं, dot syntax नहीं।
  • new() convention किसी struct के primary constructor-जैसे associated function के लिए उपयोग होता है, हालांकि यह एक special keyword नहीं है।
  • Associated functions अक्सर constructors के रूप में उपयोग होते हैं जो struct का एक नया instance return करते हैं।
🔒

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.