Rust के महत्वपूर्ण विषय

Rust Modules and pub

Organize code into modules and decide what the rest of the program may use.

  • उन्नत
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • mod and pub
  • Paths with ::
  • use and super
mod geometry
  • geometry
    • pub circle_areapublic
    • squareprivate
    • pub mod convertto_degrees

Private unless marked pub

A module groups related functions, types and constants under a name. Everything in a module is private unless it is marked pub, so a module can hide its details.

circle_area is public, but square is private and can only be called inside geometry. Paths use ::, and super refers to the parent module. use brings a name into scope so to_degrees can be called without its full path.

मुख्य बातें

  1. Everything in a module is private by default.
  2. pub makes an item usable from outside.
  3. use brings a name into scope.

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

Rust
कोड चलाएँ →
main.rs
mod geometry {
    pub const PI: f64 = 3.14159;

    pub fn circle_area(radius: f64) -> f64 {
        PI * square(radius)
    }

    fn square(value: f64) -> f64 {
        value * value
    }

    pub mod convert {
        pub fn to_degrees(radians: f64) -> f64 {
            radians * 180.0 / super::PI
        }
    }
}

use geometry::convert::to_degrees;

fn main() {
    println!("{:.2}", geometry::circle_area(2.0));
    println!("{:.1}", to_degrees(geometry::PI));
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
12.57
180.0

अभ्यास

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

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

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

अगला: Threads →

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

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

सभी चैलेंज