← Back to Rust Course | Chapter 8: Enums & Pattern Matching | Lesson 2 of 7

Option Type का उपयोग

Option बिना कभी null उपयोग किए "यहां एक value हो सकती है, या यहां कुछ नहीं हो सकता" कहने का Rust का सुरक्षित तरीका है।
Syntax
rust
enum Option<T> {
    Some(T),
    None,
}

let value: Option<Type> = Some(v);

What Is Option

Option<T> दो variants वाला एक enum है: Some(value) जब एक value मौजूद है, और None जब यह absent है। यह कई दूसरी languages में पाए null concept को replace करता है।

उदाहरण: What Is Option

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `some_number` (a `Option<i32>`), set to `Some(5)`
    let some_number: Option<i32> = Some(5);
    // Declare an immutable variable `no_number` (a `Option<i32>`), set to `None`
    let no_number: Option<i32> = None;
    // Print "{:?} and {:?}" to the console, substituting in `some_number, no_number` (with a trailing newline)
    println!("{:?} and {:?}", some_number, no_number);
}

Matching on Option

match आपको एक Option की दोनों possibilities सुरक्षित रूप से handle करने देता है, Some case में inner value निकालते हुए और None case में absence explicitly handle करते हुए।

उदाहरण: Matching on Option

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `maybe_age` (a `Option<u32>`), set to `Some(25)`
    let maybe_age: Option<u32> = Some(25);
    // Match on `maybe_age` and branch by pattern
    match maybe_age {
        Some(age) => println!("Age is {}", age),
        None => println!("No age provided"),
    }
}

Using unwrap_or for a Default

.unwrap_or(default) अगर मौजूद हो तो inner value return करता है, या अगर Option None है तो एक fallback default value, साधारण cases के लिए एक पूरे match की ज़रूरत से बचते हुए।

उदाहरण: Using unwrap_or for a Default

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `missing` (a `Option<i32>`), set to `None`
    let missing: Option<i32> = None;
    // Declare an immutable variable `value`, set to `missing.unwrap_or(0)`
    let value = missing.unwrap_or(0);
    // Print "Value: {}" to the console, substituting in `value` (with a trailing newline)
    println!("Value: {}", value);
}

Functions Returning Option

वे functions जिनके पास शायद return करने के लिए एक meaningful result न हो अपने return type के रूप में Option<T> उपयोग करते हैं, हर caller को None की possibility explicitly handle करने पर मजबूर करते हुए।

उदाहरण: Functions Returning Option

markup
// Define the function `find_even` taking `numbers` and returning a `Option<i32>`
fn find_even(numbers: &[i32]) -> Option<i32> {
    // Loop over `numbers`, binding each item to `&n`
    for &n in numbers {
        // Check whether `n % 2 == 0`
        if n % 2 == 0 {
            // Return `Some(n)` from this function
            return Some(n);
        }
    }
    None
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `nums`, set to `[1, 3, 4, 7]`
    let nums = [1, 3, 4, 7];
    // Match on `find_even(&nums)` and branch by pattern
    match find_even(&nums) {
        Some(n) => println!("Found even number: {}", n),
        None => println!("No even number found"),
    }
}
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. किसी Option<T> value को सीधे एक T की तरह उपयोग करने की कोशिश करना, पहले इसे unwrap या match किए बिना।
  2. किसी Option पर .unwrap() call करना जो None हो सकता है, जो program को runtime पर panic कराता है।
  3. यह मान लेना कि Rust में दूसरी languages की तरह एक null value है -- Rust में जानबूझकर कोई null नहीं है; Option::None उस concept को सुरक्षित रूप से replace करता है।
चैप्टर सारांश
  • Option<T> एक value represent करता है जो या तो Some(value) है या None।
  • Rust में कोई null pointers नहीं हैं; Option आपको explicitly 'no value' case handle करने पर मजबूर करता है।
  • match, if let, और .unwrap_or() जैसे combinator methods एक Option को सुरक्षित रूप से handle करने के आम तरीके हैं।
  • Option उपयोग करना 'no value' की possibility को type system में move करता है, missing-value bugs को compile time पर पकड़ते हुए।
🔒

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.