← Back to Rust Course | Chapter 10: Error Handling | Lesson 3 of 6

unwrap और expect

.unwrap() और .expect() एक Result या Option से value निकालते हैं, लेकिन अगर कोई न हो तो program को ज़ोर से crash कर देते हैं।
Syntax
rust
let value = result.unwrap();
let value = result.expect("message");
let value = result.unwrap_or(default);

Using unwrap on Result

.unwrap() सीधे Ok value निकालता है, लेकिन अगर Result असल में एक Err था तो तुरंत एक generic message के साथ panic करता है।

उदाहरण: Using unwrap on Result

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

Using unwrap on Option

.unwrap() Option पर भी वैसे ही काम करता है, Some के लिए inner value return करते हुए और None पर panic करते हुए।

उदाहरण: Using unwrap on Option

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

Using expect for Clearer Panics

.expect("message") success पर .unwrap() जैसा ही behave करता है, लेकिन failure पर यह आपके custom message को included करते हुए panic करता है, यह diagnose करना कहीं आसान बनाते हुए कि क्या गलत हुआ।

उदाहरण: Using expect for Clearer Panics

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `config` (a `Option<&str>`), set to `Some("production")`
    let config: Option<&str> = Some("production");
    // Declare an immutable variable `mode`, set to `config.expect("config value must be set")`
    let mode = config.expect("config value must be set");
    // Print "Running in {} mode" to the console, substituting in `mode` (with a trailing newline)
    println!("Running in {} mode", mode);
}

When to Avoid unwrap in Real Code

चूंकि .unwrap() और .expect() failure पर पूरे program को crash कर देते हैं, production code paths जो realistically fail हो सकते हैं उन्हें इसके बजाय errors को gracefully handle करने के लिए match, ?, या combinator methods पसंद करना चाहिए।

उदाहरण: When to Avoid unwrap in Real Code

markup
// Define the function `safe_parse` taking `s` and returning an integer
fn safe_parse(s: &str) -> i32 {
    // Match on `s.parse()` and branch by pattern
    match s.parse() {
        Ok(n) => n,
        Err(_) => 0,
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{}" to the console, substituting in `safe_parse("bad input")` (with a trailing newline)
    println!("{}", safe_parse("bad input"));
    // Print "{}" to the console, substituting in `safe_parse("77")` (with a trailing newline)
    println!("{}", safe_parse("77"));
}
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. Production code paths में .unwrap() उपयोग करना जहां failure genuinely possible है, error को gracefully handle करने के बजाय।
  2. .unwrap() के ज़रिए एक generic panic message लिखना जब .expect("clear message") failures debug करना कहीं आसान बना देता।
  3. यह मान लेना कि .unwrap() सिर्फ Result के लिए panic करता है -- यह Option::None के लिए भी panic करता है।
चैप्टर सारांश
  • .unwrap() Ok/Some की inner value return करता है, या अगर यह Err/None है तो तुरंत panic करता है।
  • .expect("message") .unwrap() जैसा behave करता है लेकिन आपको आसान debugging के लिए एक custom panic message देने देता है।
  • दोनों उन cases के लिए सबसे अच्छे हैं जहां failure सच में असंभव हो या crash पर acceptable हो, जैसे quick prototypes या tests।
  • असली production code paths में .unwrap()/.expect() के बजाय proper error handling (match, ?, या combinators) पसंद करें।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.